Documentation for java.util.concurrent.locks.ReentrantReadWriteLock

Posted by Andrei Taptunov on Stack Overflow See other posts from Stack Overflow or by Andrei Taptunov
Published on 2010-05-23T08:41:53Z Indexed on 2010/05/23 8:50 UTC
Read the original article Hit count: 402

Disclaimer: I'm not very good at Java and just comparing read/writer locks between C# and Java to understand this topic better & decisions behind both implementations.

There is JavaDoc about ReentrantReadWriteLock. It states the following about upgrade/downgrade for locks:

  • Lock downgrading ... However, upgrading from a read lock to the write lock is not possible.

It also has the following example that shows manual upgrade from read lock to write lock:

 // Here is a code sketch showing how to exploit reentrancy 
 // to perform lock downgrading after updating a cache

 void processCachedData() {
 rwl.readLock().lock();
 if (!cacheValid) {
    // upgrade lock manually
    #1: rwl.readLock().unlock();   // must unlock first to obtain writelock
    #2: rwl.writeLock().lock();
    if (!cacheValid) { // recheck
       ...
    }
   ...
 }
 use(data);
 rwl.readLock().unlock();

Does it mean that actually the sample from above may not behave correctly in some cases - I mean there is no lock between lines #1 & #2 and underlying structure is exposed to changes from other threads. So it can not be considered as the correct way to upgrade the lock or do I miss something here?

© Stack Overflow or respective owner

Related posts about java

Related posts about reentrantreadwritelock