ReentrantReadWriteLock: what's the difference between ReadLock and WriteLock?
readLock.lock();
- This means that if any other thread is writing (i.e. holds a write lock) then stop here until no other thread is writing.
- Once the lock is granted no other thread will be allowed to write (i.e. take a write lock) until the lock is released.
writeLock.lock();
- This means that if any other thread is reading or writing, stop here and wait until no other thread is reading or writing.
- Once the lock is granted, no other thread will be allowed to read or write (i.e. take a read or write lock) until the lock is released.
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.