Reputation: 2488
In ReentrantReadWriteLock
documentation it is said:
writer can acquire the read lock, but not vice-versa
If I understand correctly it means that from the same thread you can execute:
//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")
This makes sense: if you already locked write
no other thread can enter the locked code. But if you locked read
, why can't you enter the write
block in the same thread if no other thread make read
lock? So this doesn't work:
//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")
Why do you have to unlock the read
before locking write
in the same thread?
Upvotes: 4
Views: 2546
Reputation: 27115
I don't actually know the answer, but it may be to help you avoid writing code that can deadlock.
Suppose you have two threads that execute the same code. Both threads have acquired a read lock. Then, both threads attempt to acquire the write lock. Neither thread will be able to proceed until the other thread releases its read lock, but neither thread will release it's read lock while it's waiting to upgrade.
A different implementation could detect the deadlock, and throw exceptions in both threads when it is discovered, but maybe someone thought that would either (A) adversely impact the performance for applications that do not require deadlock detection, or (B) complicate the API too much.
By disallowing you to upgrade a read lock to a write lock, they've made it impossible for you to write a program that deadlocks in that particular way.
Upvotes: 0
Reputation: 1370
ReentrantReadWriteLock doesn't mean that the normal rules locking are not followed.
If a thread acquired a lock for reading purpose, it expects the value of the target data not to change for the duration of the lock. Having otherwise would prevent repeatable-reads. Conceptually, if you let a thread (the same or another) acquire a write lock when a read lock is out, you are breaching that rule.
If a thread acquired a lock for writing, it implicitly has reading rights as well, so acquisition of a read-lock can be granted because it doesn't really breach the contract of the lock (if I can write, I can read) nor the expectations of the lock holder (I locked for writing so I am the only one that can read or write now).
Upvotes: 5