What I know is:
ReadLock
and WriteLock
affect each other somehowWriteLock
is just like synchronized
ReadLock
seems cannot work aloneAn update lock is an exclusive lock, that is, only one lock can be held at a time. It is used to prevent concurrent updates. A read lock is a shared lock, multiple readers can held a read lock simultaneously.
This lock supports a maximum of 65535 recursive write locks and 65535 read locks.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
Reentrant Locks are provided in Java to provide synchronization with greater flexibility. What are Reentrant Locks? The ReentrantLock class implements the Lock interface and provides synchronization to methods while accessing shared resources.
Combining these you can arrange for only one thread at a time to have write access, but as many readers as you like can read at the same time except when a thread is writing.
Put another way. Every time you want to read from the structure, take a read lock. Every time you want to write, take a write lock. This way whenever a write happens no-one is reading (you can imagine you have exclusive access), but there can be many readers reading at the same time so long as no-one is writing.
The documentation for ReadWriteLock
makes this clear:
A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. 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. This is useful if you've got some resource which is safe to read from multiple threads, and where reading is much more common than writing, but when the resource is not actually read-only. (If there are no writers and reading is safe, there's no need for a lock at all.)
When a thread acquires a WriteLock
, no other thread can acquire the ReadLock
nor the WriteLock
of the same instance of ReentrantReadWriteLock
, unless that thread releases the lock. However, multiple threads can acquire the ReadLock
at the same time.
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