Introduction
The Java StampedLock class joined the JDK in Java 8 (2014) as part of JSR 337. It is a specialised reader-writer lock that adds an optimistic read mode on top of the standard read and write modes. Optimistic reads do not increment the reader counter; they observe the lock state at the start and validate it at the end, paying no synchronisation cost on the read path when there is no concurrent write. The trade-off is that optimistic reads can fail and require a retry, but the common case becomes essentially free.
For a Java learner, the java stampedlock primitive is the right tool for read-mostly workloads where ReentrantReadWriteLock's reader counter overhead is the bottleneck. The classic example is a high-traffic cache that reads millions of times per second and writes a few times per minute. This post walks through the optimistic validation mechanics, demonstrates a thread-safe point class, and shows the downgrade pattern from write to read.
What is Java StampedLock?
The Java StStampedLock class exposes three operations: writeLock returns a long stamp and acquires the write lock; readLock returns a long stamp and acquires the read lock; tryOptimisticRead returns a long stamp that is a snapshot of the current state without blocking. Validation happens via validate(stamp), which returns true if the stamp is still valid (no write has occurred since the stamp was issued). If validate returns false, the optimistic read failed and the caller must either retry or fall back to a real read lock.
Conceptually, StampedLock is a more aggressive version of ReadWriteLock. Where ReadWriteLock guarantees correctness by serialising reads with writes, StampedLock bets that writes are rare and validates after the read. When the bet pays off, the read avoids all contention; when it fails, the caller pays the cost of a retry. StampedLock is not reentrant: a thread holding the write lock that calls writeLock again deadlocks. It also has no Condition support; for condition waits, use ReentrantReadWriteLock.
The stamp is a long that encodes the lock state at the moment of acquisition. For optimistic reads, the stamp is just a snapshot of the state; for real reads and writes, the stamp identifies the lock acquisition and is required for the matching unlock.
How Java StampedLock Works - Step by Step
Step 1: Construction. You write new StampedLock. There is no fairness flag; StampedLock is always non-fair to maximise throughput.
Step 2: tryOptimisticRead. Returns a non-zero stamp if no writer is active, or zero if a writer is active. The call is a single volatile read of the state, with no CAS and no increment; it is the fastest possible "snapshot" operation.
Step 3: Read fields into locals. The caller reads the data it needs into local variables. The optimistic stamp does not prevent a write from happening concurrently; the data may be inconsistent at this point.
Step 4: validate(stamp). Returns true if no write has occurred since tryOptimisticRead was called. Validate is a volatile read followed by a memory fence; the fence guarantees that the field reads in step 3 are visible before the validate check. If validate returns true, the local values are consistent and can be used. If validate returns false, the read failed.
Step 5: Fallback. On a failed optimistic read, the caller can either retry the optimistic protocol or acquire a real read lock. The standard idiom is to retry a bounded number of times optimistically, then fall back to readLock to guarantee forward progress.
Step 6: writeLock and readLock. These acquire the lock in the traditional way and return a stamp. unlock(stamp) releases the lock; the stamp must be the one returned by the matching acquire call. The write lock can downgrade to a read lock via tryConvertToReadLock(stamp), which atomically trades the write lock for a read lock without releasing exclusivity in between.
Java Program for StampedLock
import java.util.concurrent.locks.StampedLock;
public class StampedLockDemo {
static final class Point {
private double x, y;
private final StampedLock lock = new StampedLock();
void move(double deltaX, double deltaY) {
long stamp = lock.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
lock.unlockWrite(stamp);
}
}
double distanceFromOrigin() {
long stamp = lock.tryOptimisticRead();
double xRead = x;
double yRead = y;
if (!lock.validate(stamp)) {
// optimistic read failed; fall back to a real read lock
stamp = lock.readLock();
try {
xRead = x;
yRead = y;
} finally {
lock.unlockRead(stamp);
}
}
return Math.sqrt(xRead * xRead + yRead * yRead);
}
double currentX() {
long stamp = lock.readLock();
try {
return x;
} finally {
lock.unlockRead(stamp);
}
}
}
public static void main(String[] args) throws InterruptedException {
Point p = new Point();
p.move(3, 4);
System.out.println("distance from origin: " + p.distanceFromOrigin());
Thread mover = new Thread(() -> {
for (int i = 0; i < 5; i++) {
p.move(1, 0);
System.out.println("moved to x=" + p.currentX());
}
});
Thread reader = new Thread(() -> {
for (int i = 0; i < 5; i++) {
double d = p.distanceFromOrigin();
System.out.println("distance now " + d);
}
});
mover.start();
reader.start();
mover.join();
reader.join();
}
}
Code Explanation - Line by Line
The Point class stores two doubles and protects them with a StampedLock. The move method uses the write lock: writeLock returns a stamp, the increments happen under exclusivity, and unlockWrite releases. The stamp is checked by unlockWrite, so passing a wrong stamp would throw an exception.
The distanceFromOrigin method uses the optimistic pattern. tryOptimisticRead returns a snapshot of the lock state; the caller reads x and y into locals without holding any lock. Then validate checks whether a write happened between tryOptimisticRead and the field reads. The validation must come after the field reads because the validate fence orders the field reads before the validate check.
If validate returns false, the optimistic read failed and the values in xRead and yRead may be inconsistent. The fallback acquires a real read lock, reads the fields again under that lock, and unlocks. The fallback is required to guarantee forward progress; without it, a continuous stream of writes could cause infinite optimistic retries.
The currentX method uses the plain read lock for a single field read where the optimistic pattern is not worth the validation overhead. For one field, a single real read lock is simpler and equally fast in the no-contention case.
The main method demonstrates a starting distance computation, then runs a mover thread and a reader thread concurrently. The mover calls move(1, 0) five times, incrementing x each time; the reader calls distanceFromOrigin five times. Some optimistic reads may fail and fall back; some may succeed. The output shows the distance growing as the mover thread runs.
Sample Input and Output
Input: Point starts at (0, 0); main moves to (3, 4); then mover adds 5 to x while reader computes 5 distances Output (interleaving will vary): distance from origin: 5.0 moved to x=4.0 distance now 5.0 moved to x=5.0 distance now 6.4031242374328485 moved to x=6.0 exchanger demo done
The first distance is 5.0 because the point is at (3, 4) and sqrt(9 + 16) is 5. As the mover increments x, the distance grows; readers see a mix of pre-move and post-move values, and the optimistic reads that succeed return those mixed values.
Common Mistakes to Avoid
Mistake 1: Using the field values without validating the stamp. The optimistic read pattern is only correct if you validate after reading. Skipping the validate turns a correct optimistic read into a data race.
Mistake 2: Reading fields after validate. The order must be snapshot, read fields, validate. If you snapshot, validate, then read fields, a write between the snapshot and the validate can be missed, and the field reads can see inconsistent values.
Mistake 3: Treating StampedLock as reentrant. It is not. A thread holding the write lock that calls writeLock again will deadlock. StampedLock is designed for short, non-reentrant sections; for reentrant mutual exclusion use ReentrantLock.
Mistake 4: Forgetting to unlock on every exit path. unlockWrite and unlockRead take a stamp argument; if you call unlock with the wrong stamp, the lock state becomes corrupt. Always unlock in a finally, and never reuse a stamp across multiple lock acquisitions.
Real-World Applications
High-throughput caches. The Java 8 ConcurrentHashMap internally uses stamped-lock-style optimistic reads in some paths, and many high-performance cache implementations (Caffeine, for example, in some versions) adopted the same pattern for read-mostly entries.
Spatial indexes. Geometry and GIS libraries that store point clouds or quad-trees use StampedLock to keep read paths cheap; the optimistic read pattern is well-suited because writes (insertions) are rare compared to reads (queries).
Financial market data. Order book and price feed handlers use StampedLock for the snapshot of the current best bid and ask; millions of reads per second, occasional updates, and a strict requirement that a read returns a consistent snapshot.
Configuration hot reload. A configuration object that is read on every request and reloaded rarely can use StampedLock so the read path is just a volatile read plus a validate; the writer pays the cost of the actual swap.
Game state. Game engines that publish per-frame snapshots to renderer threads use StampedLock on the snapshot itself; the snapshot is read by N renderers and written by the single simulation thread.
Conclusion
StampedLock adds optimistic reads to the read-write pattern, making the common no-write case essentially free while still guaranteeing correctness on the rare write. It is the right choice for read-mostly workloads where ReentrantReadWriteLock's reader counter is the bottleneck. The next topics worth studying are ReentrantReadWriteLock for reentrant, condition-supporting read-write locks, ReentrantLock for plain mutual exclusion, and the VarHandle class which underlies the optimistic pattern.
Comments
Comments
Post a Comment