Please explain me more the contract. I can't figure out if two locks contained in ReentrantReadWriteLock
somehow related? Or these are just a bundle of two normal locks?
The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. So you can have many readers at a time, but only one writer - and the writer will prevent readers from reading, too.
With the Exclusive Lock, a data item can be read as well as written. Also called write lock.
ReadWriteLock is an advanced thread lock mechanism. It allows multiple threads to read a certain resource, but only one to write it, at a time. The idea is, that multiple threads can read from a shared resource without causing concurrency errors.
In many situations, data is read more often than it is modified or written. In these cases, you can allow threads to read concurrently while holding the lock and allow only one thread to hold the lock when data is modified. A multiple-reader single-writer lock (or read/write lock) does this.
It allows multiple threads to read a resource concurrently, but requires a thread to wait for an exclusive lock in order to write to the resource.
Rules are:
Internally the lock state (c) is maintained by an int value. In this case, since we have read and write locks, it is logically divided into two shorts: The lower one representing the exclusive (writer) lock hold count, and the upper the shared (reader) hold count.
Assuming current state of lock is c= xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy then Number of reader locks are the upper bits xxxx xxxx xxxx xxxx
Number of writer locks are the lower bits yyyy yyyy yyyy yyyy
If threads are waiting Read Lock it is shared but when thread wants to acquire write lock only that thread is allowed the access same as mutual exclusion.
So either one of operation is allowed .if lock is held by readers and thread request write lock no more readers are allowed to acquire read lock until thread which has acquired write lock release it
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With