Why in ReentrantReadWriteLock, should the readLock() be unlocked before writeLock().lock()?

The problem with upgrading a read lock to a write lock is, if two threads try to do it at the same time, it can lead to deadlock. Consider the following sequence:

  1. Thread A: acquires read lock
  2. Thread B: acquires read lock (Note that both threads now share the read lock).
  3. Thread A: tries to acquire write lock (blocks as thread B holds read lock)
  4. Thread B: tries to acquire write lock (blocks as thread A holds read lock)

Now there is a deadlock. Neither thread A or B can proceed, and neither will ever release the read lock.


The Javadoc explicitly states upgrading a read lock to a write lock is not possible. The reason for that is because it can create a deadlock.

  • thread 1 acquire read lock
  • thread 2 acquire read lock
  • thread 1 ask to upgrade lock to write
  • thread 2 ask to upgrade lock to write

Both threads are now waiting on each other ... forever.


Reentrancy allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible (which results in a deadlock).

Source: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html