Understanding StampedLock in Java 8: Principles and Practical Use
This article explains Java 8's StampedLock—its optimistic and pessimistic read/write modes, internal state handling, source‑code walkthrough, typical usage scenarios, and a performance comparison with ReentrantLock and ReentrantReadWriteLock—providing concrete code examples and detailed analysis for developers.
Java provides a rich set of concurrency tools, and the Java 8 concurrency library (JUC) includes a newer lock mechanism called StampedLock.
1. StampedLock Overview
StampedLock, introduced in Java 8, offers optimistic read locks and pessimistic read‑write locks. Compared with ReentrantLock and ReentrantReadWriteLock, it can deliver significantly higher concurrency performance because the optimistic read strategy allows multiple threads to read shared data without blocking.
2. How StampedLock Works
StampedLock resides in java.util.concurrent.locks and maintains a single long state variable that encodes the lock type (read or write) and a version stamp. When a thread requests a lock, StampedLock examines the current state and returns a stamp that must be supplied when releasing the lock.
Two read‑lock types are provided:
Optimistic read lock : multiple threads can read concurrently without blocking; suitable for read‑heavy, write‑light scenarios, but may see inconsistent data if a write occurs.
Pessimistic read lock : blocks writers while reading, guaranteeing consistency.
2.1 Core Concepts
Lock state : a long variable holds both the lock status and a version stamp.
Optimistic read : the thread checks whether a write lock is held; if not, it returns the current state as a stamp. The lock does not block other threads.
Pessimistic read : the thread acquires a read lock that blocks writers until the lock is released.
Write lock : exclusive; only one thread may hold it. Other threads block until it is released.
Re‑entrancy : StampedLock tracks per‑thread lock counts, allowing the same thread to reacquire the lock without deadlock.
Lock conversion : a thread can upgrade an optimistic read to a pessimistic read or a write lock, provided no other thread acquires the conflicting lock during the conversion.
2.2 Source‑code Analysis
The lock state is stored in a long field named state:
Key constants:
private final long WRITER_MASK = 0x8000000000000000L; // write‑lock flag
private final long NOT_LOCKED = 0L; // unlocked state
private volatile long state; // lock state variableOptimistic read implementation:
public long tryOptimisticRead() {
long s = state; // snapshot of current state
if ((s & WRITER_MASK) != 0L) {
return 0L; // write lock held, fail
} else {
return s; // return stamp, no state change
}
}Write‑lock acquisition (simplified):
private boolean acquireWrite(boolean interruptible, long deadline) {
long s = state, next;
while ((s & WRITER_MASK) != 0L || (next = tryIncWriter(s)) == 0L) {
// wait or abort based on interruptible/deadline
}
// set owner info and return true (details omitted)
} tryIncWriterattempts to increment the writer counter and returns 0 on failure.
3. Usage Scenarios
StampedLock shines in read‑dominant workloads where strict consistency is not required, such as caching systems where many threads read a cached value while few update it. In write‑heavy or strong‑consistency scenarios, traditional locks may be preferable.
4. Practical Example
import java.util.concurrent.locks.StampedLock;
public class StampedLockExample {
private final StampedLock stampedLock = new StampedLock();
private int balance = 0;
// Optimistic read with fallback to pessimistic read
public int getBalanceWithOptimisticReadLock() {
long stamp = stampedLock.tryOptimisticRead();
int currentBalance = balance;
if (!stampedLock.validate(stamp)) {
stamp = stampedLock.readLock();
try {
currentBalance = balance;
} finally {
stampedLock.unlockRead(stamp);
}
}
return currentBalance;
}
// Pessimistic read
public int getBalanceWithPessimisticReadLock() {
long stamp = stampedLock.readLock();
try {
return balance;
} finally {
stampedLock.unlockRead(stamp);
}
}
// Write lock
public void updateBalanceWithWriteLock(int amount) {
long writeStamp = stampedLock.writeLock();
try {
balance += amount;
} finally {
stampedLock.unlockWrite(writeStamp);
}
}
public static void main(String[] args) {
StampedLockExample example = new StampedLockExample();
Runnable readTask = () -> {
int b = example.getBalanceWithOptimisticReadLock();
System.out.println("Read balance (optimistic): " + b);
};
Runnable writeTask = () -> {
example.updateBalanceWithWriteLock(100);
System.out.println("Updated balance (write): " + example.getBalanceWithPessimisticReadLock());
};
new Thread(readTask).start();
new Thread(readTask).start();
new Thread(writeTask).start();
}
}The example defines three methods: getBalanceWithOptimisticReadLock: tries an optimistic read and falls back to a pessimistic read if validation fails. getBalanceWithPessimisticReadLock: acquires a read lock that blocks writers. updateBalanceWithWriteLock: acquires an exclusive write lock to modify the shared balance variable.
5. Comparison with Other Locks
Compared with ReentrantLock and ReentrantReadWriteLock, StampedLock delivers higher concurrency performance thanks to its optimistic read strategy, which allows multiple readers to proceed without blocking. It also supports re‑entrancy and fair‑lock options, but its API is more complex and requires careful handling of the stamp values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
