StampedLock
Learn how to use the StampedLock class for optimistic read, write and read access.
We'll cover the following
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Code widgets in this lesson may fail to execute, if Educative.io’s code execution platform doesn’t use Java version 9 or above. This is because the
StampedLock
class was introduced in Java 9.
Overview
The StampedLock
was introduced in Java 9 and is a capability-based lock with three modes for controlling read/write access.
The StampedLock
class is designed for use as an internal utility in the development of other thread-safe components. Its use relies on knowledge of the internal properties of the data, objects, and methods it protects.
Modes
The state of a StampedLock
is defined by a version and mode. There are three modes the lock can be in:
- Writing
- Reading
- Optimistic Reading
On acquiring a lock, a stamp (long value) is returned that represents and controls access with respect to a lock state. The stamp can be used later on to release the lock or convert the existing acquired lock to a different mode.
Reading
The read mode can be acquired using the readLock()
method. When reading a thread isn’t expected to make any changes to the shared state and therefore it makes sense to have multiple threads acquire the read lock at the same time. The method returns a stamp that can be used to unlock the read lock. Timed and untimed versions of tryReadLock()
also exist.
The code widget below demonstrates multiple threads acquiring the StampedLock
in read mode.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy