What is a ReentrantReadWriteLock upgrade / downgrade?

What is a ReentrantReadWriteLock upgrade / downgrade? I see javadoc about update / downgrade:

“Lock down: Reentrancy also allows you to switch from a write lock to a read lock by acquiring a write lock, then a read lock and then releasing a write lock. However, updating from a read lock to a write lock is not possible.

And sample provided by:

 class CachedData { Object data; volatile boolean cacheValid; ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // upgrade lock manually rwl.readLock().unlock(); // must unlock first to obtain writelock rwl.writeLock().lock(); if (!cacheValid) { // recheck data = ... cacheValid = true; } // downgrade lock rwl.readLock().lock(); // reacquire read without giving up write lock rwl.writeLock().unlock(); // unlock write, still hold read } use(data); rwl.readLock().unlock(); } } 

I know this speaks of the relationship between readLock and writeLock, but I could not get a clear concept from the document. Could you give me a little more explanation? Thanks!

+8
java concurrency locking upgrade
source share
1 answer

I believe that in this context the idea of ​​“modernizing” and “downgrading” is based on the idea that blocking the reader is, in a sense, a “weaker” blocking than blocking the writer. When a write lock is obtained, no other threads will be able to obtain a lock in any form, while when a reader is locked, any other thread can get a read lock if it wants.

Here, “lowering” the lock means that if you hold a write lock, you can switch to holding only a read lock by receiving a read lock and then letting go of the write lock. This means that you may have a thread that starts doing something critical (to prevent other threads from reading), does its job, and then switches to a lower priority lock (read lock) without being without a lock, This allows you to hold the lock continuously without unloading it.

However, the other way does not work - after you hold the read lock, you cannot “refresh” by holding the more important write lock, trying to get the write lock. If you try to do this, the thread will simply be blocked until it is interrupted.

Hope this helps!

+12
source share

All Articles