Question

In the current issue of the German Java Magazine there is a code example how ReentrantReadWriteLock (I guess ReadWriteLock in general) is often used incorrectly. Unfortunately the author does not care to explain why.

private static final ReadWriteLock lock = new ReentrantReadWriteLock();

// #1: correct use
lock.writeLock().lock(); 
try {
  // do stuff 
} finally {
  lock.writeLock().unlock();
}

// #2: incorrect use
try {
  lock.writeLock().lock(); 
  // do stuff 
} finally {
  lock.writeLock().unlock();
}

// #3: incorrect use
lock.writeLock().lock(); 
// do stuff 
lock.writeLock().unlock(); 

I can see why #3 is wrong. But whats the difference between #1 and #2? Assuming that lock.writeLock().lock(); does not throw (edit: wrong assumption, see the accepted answer), these versions look equal to me.

Was it helpful?

Solution

Look at the Javadoc for Lock.lock()

Implementation Considerations

A Lock implementation may be able to detect erroneous use of the lock, such as an invocation that would cause deadlock, and may throw an (unchecked) exception in such circumstances. The circumstances and the exception type must be documented by that Lock implementation.

Emphasis mine.

So by the contract it is allowed to throw an Exception. This explains why the the second approach is wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top