ReentrantReadWriteLock

This class is an implementation of ReadWriteLock. ReadWriteLock is a lock that can be used for parallel read access and exclusive write access. It means that several threads can read the resource protected by the lock, but when a thread writes the resource, no other thread can get access to it, not even read during that period. A ReadWriteLock is simply two Lock objects returned by the readLock and writeLock methods. To get read access on ReadWriteLock, the code has to invoke myLock.readLock().lock(), and to get access to write lock, myLock.writeLock().lock(). Acquiring one of the locks and releasing it in the implementation is coupled with the other lock. To acquire a write lock, no thread should have an active read lock, for example.

There are several intricacies in the use of the different lock. For example, you can acquire a read lock, but you cannot get a write lock so long as you have the read lock. You have to release the read lock first to acquire a write lock. This is just one of the simple details, but this is the one that novice programmers have trouble with many times. Why is it implemented this way? Why should the program get a write lock, which is more expensive—in sense of higher probability locking other threads—when it still is not sure that it wants to write the resource? The code wants to read it and. based on the content. it may later decide that it wants to write it.

The issue is not with the implementation. The developers of the library decided this rule, not because they just liked it that way or because they were aware of parallel algorithms and deadlock possibilities. When two threads have read lock and each decides to upgrade the lock to write lock, then they would intrinsically create a deadlock. Each would hold the read lock waiting for the write and none of them would get it ever.

On the other end, you can downgrade a write lock to a read lock without risking that in the meantime somebody acquires a write lock and modifies the resource.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.133.49