4

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.

1 Answer 1

5

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.

2
  • Ah I see, did not catch that. So I guess calling unlock() after an unsuccessful lock() is not allowed?. Nvm: A Lock implementation will usually impose restrictions on which thread can release a lock (typically only the holder of the lock can release it) and may throw an (unchecked) exception if the restriction is violated. Any restrictions and the exception type must be documented by that Lock implementation. Mar 22, 2014 at 23:08
  • @atamanroman the lock is reentrant - if your Thread holds two locks and accidentally unlocks the wrong one... And yeah, the implementation is free to throw an unchecked exception if you try and unlock without holding the lock. Mar 22, 2014 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.