The ReentrantReadWriteLock and its drawbacks

Before Java 8 we had a ReentrantReadWriteLock class that was used for reading and writing data in a thread-safe manner.

Here are a few of the important points about ReentrantReadWriteLock:

  1. Multiple threads can acquire a read lock simultaneously.
  2. Only one thread can acquire a write lock.
  3. If a thread wants to acquire a write lock and there are some threads that have read lock, the thread will wait until all the threads release the read lock.

There are a few problems with using the ReentrantReadWriteLock class:

  1. It can lead to starvation.
  2. Sometimes it can be significantly slower than other synchronizers.

The improvements provided by StampedLock

To overcome these disadvantages, StampedLock is added. Apart from providing separate read and write locks, also has a feature for optimistic locking for reading operations.

StampedLock also provides a method to upgrade read lock to write lock, which is not in ReentrantReadWriteLock in Java.

The StampedLock class provides three locking modes:

  1. Read
  2. Write
  3. Optimistic read

Let’s look at a basic example of StampedLock. In the below example we have used a few operations that are available in the StampedLock class.

a) readLock() - This method is used to acquire the read lock. This method returns a stamp that should be used while releasing the lock.

b) unlockRead(long stamp) - This method is used to release the read lock. This method takes a stamp as an input. If the stamp provided does not match, IllegalStateException is thrown.

a) writeLock() - This method is used to acquire the write lock. This method returns a stamp that should be used while releasing the lock.

b) unlockWrite(long stamp) - This method is used to release the write lock. This method takes a stamp as an input. If the stamp provided does not match then IllegalStateException is thrown.

Get hands-on with 1200+ tech skills courses.