StampedLock
This lesson introduces a new kind of Lock class introduced in Java 8.
The ReentrantReadWriteLoc
k 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
:
- Multiple threads can acquire a read lock simultaneously.
- Only one thread can acquire a write lock.
- 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:
- It can lead to starvation.
- 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:
- Read
- Write
- 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, IllegalStateExceptio
n 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 1400+ tech skills courses.