StampedLock
StampedLock (Java 8) is a lock built for data that is read far more often than it is written. Its key feature is the optimistic read: read without locking at all, then check whether a writer interfered. This page explains what a stamp is, runs each mode, proves why the check is necessary, shows the traps that come from the lock having no owner and no reentrancy, and measures how much optimistic reads save.
Contents
How StampedLock works
java.util.concurrent.locks.StampedLocklonglong
That design gives three modes:
- Writing:
is exclusive, like a write lock inwriteLock() .ReentrantReadWriteLock - Reading:
is shared; many readers may hold it at once.readLock() - Optimistic reading:
takes no lock at all. It only returns the current version, or 0 if a writer holds the lock. The reader copies the fields it needs and then callstryOptimisticRead() , which returns true only if no write lock was acquired since the stamp was issued. If validation fails, the reader discards its copy and tries again, usually with a real read lock.validate(stamp)
An optimistic read writes nothing to shared memory. A read lock, by contrast, must increment and decrement the reader count, so every reader on every core writes to the same cache line. On read-heavy data that difference is large, as the measurements below show. The price is a harder API: the lock is not reentrant, has no owner thread and supports no Condition
| Mode | Acquire | Release | Blocks writers? | Best for |
|---|---|---|---|---|
| Write | writeLock()tryWriteLock()writeLockInterruptibly() | unlockWrite(stamp) | Yes, exclusive | Changing the state |
| Read | readLock()tryReadLock()readLockInterruptibly() | unlockRead(stamp) | Yes | Long reads, or the fallback after a failed optimistic read |
| Optimistic | tryOptimisticRead() | Nothing; check with validate(stamp) | No | Short reads of a few fields |
| Conversion | tryConvertToWriteLocktryConvertToReadLocktryConvertToOptimisticRead | Use the returned stamp | Depends on the target mode | Read, then write only if needed |
The programs below were tested on JDK 21.
The three modes on a point
The Javadoc's own example is a point with xydistanceFromOrigin(true)
import java.util.concurrent.locks.StampedLock;
public class Modes {
private double x;
private double y;
private final StampedLock lock = new StampedLock();
void move(double dx, double dy) {
long stamp = lock.writeLock(); // exclusive
try {
x += dx;
y += dy;
} finally {
lock.unlockWrite(stamp);
}
}
// Optimistic read: no lock at all, then check whether a write happened meanwhile
double distanceFromOrigin(boolean simulateConcurrentWrite) {
long stamp = lock.tryOptimisticRead();
double cx = x;
double cy = y;
if (simulateConcurrentWrite) {
move(1, 1); // a "concurrent" write between read and check
}
if (!lock.validate(stamp)) { // a write happened: fall back to a read lock
System.out.println(" optimistic read invalidated, retrying with a read lock");
stamp = lock.readLock();
try {
cx = x;
cy = y;
} finally {
lock.unlockRead(stamp);
}
} else {
System.out.println(" optimistic read was valid, no lock taken");
}
return Math.hypot(cx, cy);
}
// Upgrade: read first, convert to a write lock only if a change is needed
void moveIfAtOrigin(double nx, double ny) {
long stamp = lock.readLock();
try {
while (x == 0.0 && y == 0.0) {
long ws = lock.tryConvertToWriteLock(stamp);
if (ws != 0L) { // conversion succeeded
stamp = ws;
x = nx;
y = ny;
System.out.println(" converted read lock to write lock and moved");
break;
}
lock.unlockRead(stamp); // could not convert: take the write lock
stamp = lock.writeLock();
}
} finally {
lock.unlock(stamp);
}
}
public static void main(String[] args) {
Modes p = new Modes();
p.moveIfAtOrigin(3, 4);
System.out.println("distance: " + p.distanceFromOrigin(false));
System.out.println("distance: " + p.distanceFromOrigin(true));
// Stamps and state
long w = p.lock.writeLock();
System.out.println("isWriteLocked " + p.lock.isWriteLocked()
+ ", optimistic read now: " + p.lock.tryOptimisticRead() + " (0 = not possible)");
p.lock.unlockWrite(w);
long r1 = p.lock.readLock();
long r2 = p.lock.readLock();
System.out.println("two read stamps held at once, read count " + p.lock.getReadLockCount());
p.lock.unlockRead(r1);
p.lock.unlockRead(r2);
}
}
Output:
converted read lock to write lock and moved
optimistic read was valid, no lock taken
distance: 5.0
optimistic read invalidated, retrying with a read lock
distance: 6.4031242374328485
isWriteLocked true, optimistic read now: 0 (0 = not possible)
two read stamps held at once, read count 2
took a read lock, saw the point at the origin, and converted the read lock to a write lock in place withmoveIfAtOrigin . Conversion succeeds when this thread is the only reader; otherwise it returns 0, and the code releases the read lock, takes the write lock and checks again in the loop.tryConvertToWriteLock- The first optimistic read was valid, so the distance 5.0 was computed from (3, 4) with no lock taken.
- In the second read, the write moved the point to (4, 5) after the fields were copied.
returned false, the code retried under a read lock, and the result, 6.403, is the distance of (4, 5).validate - While the write lock is held,
returns 0, which can never validate. Two read stamps can be held at once, as the read count of 2 shows; each must be released with its own stamp.tryOptimisticRead()
Converting between modes
The conversion methods move a stamp from one mode to another without releasing the lock in between, when that is possible. The program converts in every direction, including one case that must fail because a second reader is present.
import java.util.concurrent.locks.StampedLock;
public class Conversion {
public static void main(String[] args) throws InterruptedException {
StampedLock lock = new StampedLock();
// 1. Only reader: read -> write conversion succeeds in place
long r = lock.readLock();
long w = lock.tryConvertToWriteLock(r);
System.out.println("1. sole reader converts to write: " + (w != 0)
+ ", isWriteLocked " + lock.isWriteLocked());
// 2. Write -> read: always possible, lets other readers in again
long r2 = lock.tryConvertToReadLock(w);
System.out.println("2. write converts to read: " + (r2 != 0)
+ ", read count " + lock.getReadLockCount());
// 3. A second reader present: conversion to write fails and returns 0
long[] other = new long[1];
Thread reader = new Thread(() -> other[0] = lock.readLock());
reader.start();
reader.join();
long failed = lock.tryConvertToWriteLock(r2);
System.out.println("3. with 2 readers, convert to write returns " + failed
+ "; the original read stamp is still held");
lock.unlockRead(other[0]);
lock.unlockRead(r2);
// 4. Optimistic -> write: succeeds if nothing changed since the stamp
long opt = lock.tryOptimisticRead();
long w2 = lock.tryConvertToWriteLock(opt);
System.out.println("4. optimistic converts to write: " + (w2 != 0));
// 5. Write -> optimistic: releases the lock and returns a valid optimistic stamp
long opt2 = lock.tryConvertToOptimisticRead(w2);
System.out.println("5. write converts to optimistic: valid " + lock.validate(opt2)
+ ", isWriteLocked " + lock.isWriteLocked());
}
}
Output:
1. sole reader converts to write: true, isWriteLocked true
2. write converts to read: true, read count 1
3. with 2 readers, convert to write returns 0; the original read stamp is still held
4. optimistic converts to write: true
5. write converts to optimistic: valid true, isWriteLocked false
- A read stamp converted to a write stamp because no other reader held the lock. This is the upgrade that
cannot do at all.ReentrantReadWriteLock - Converting a write stamp to a read stamp always works and lets other readers in while this thread keeps reading a state no writer can change.
- With a second reader holding the lock, the upgrade returned 0. The original read stamp was still valid and had to be released normally. Code that upgrades must therefore always have a fallback: release the read lock, take the write lock, and check the condition again.
- An optimistic stamp converted straight to a write lock, because no write had happened since it was issued.
- Converting a write stamp to an optimistic stamp released the lock and returned a stamp that validates, until the next writer comes along.
Every conversion returns a new stamp. Keep using the returned stamp for the next unlock or conversion; the old one becomes invalid on success.
Why validate() is not optional
During an optimistic read, a writer can be halfway through an update. The reader may then copy a mix of old and new values. Here a writer keeps the invariant x == y
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.StampedLock;
public class Validate {
// Invariant kept by the writer: x == y at every unlock
static long x;
static long y;
static final StampedLock LOCK = new StampedLock();
public static void main(String[] args) throws InterruptedException {
AtomicBoolean stop = new AtomicBoolean();
Thread writer = new Thread(() -> {
while (!stop.get()) {
long s = LOCK.writeLock();
try {
x++;
Thread.onSpinWait(); // a moment where x != y
y++;
} finally {
LOCK.unlockWrite(s);
}
}
});
writer.start();
long reads = 0;
long tornBeforeValidate = 0;
long rejected = 0;
long acceptedButTorn = 0;
long end = System.nanoTime() + 500000000L;
while (System.nanoTime() < end) {
long stamp = LOCK.tryOptimisticRead();
long cx = x; // copy into locals...
long cy = y;
reads++;
if (cx != cy) {
tornBeforeValidate++; // ...which may be inconsistent here
}
if (!LOCK.validate(stamp)) {
rejected++; // a write overlapped: discard the copy
continue;
}
if (cx != cy) {
acceptedButTorn++; // never happens after a valid stamp
}
}
stop.set(true);
writer.join();
System.out.println("optimistic reads in 0.5 s: more than 100,000: " + (reads > 100000));
System.out.println("saw x != y before validate: " + (tornBeforeValidate > 0));
System.out.println("validate() rejected some reads: " + (rejected > 0));
System.out.println("accepted reads with x != y: " + acceptedButTorn);
}
}
Output:
optimistic reads in 0.5 s: more than 100,000: true
saw x != y before validate: true
validate() rejected some reads: true
accepted reads with x != y: 0
- Before validation, the reader did see
: the copied pair was torn, half from before the write and half from after.x != y rejected those reads, and not a single accepted read broke the invariant. The exact counts change every run, so the program prints only whether each case occurred.validate - The rule that follows: in the optimistic section, only copy fields into local variables. Do not call methods on them, index arrays with them or follow references, because the values may be inconsistent and can cause exceptions or infinite loops before you get a chance to validate. Use the copies only after
returns true.validate - An optimistic read reads plain fields without
. That is safe becausevolatile includes a memory fence, as documented in its Javadoc, and the version check catches any write that overlapped.validate
Traps: no reentrancy, no owner, no conditions
StampedLockReentrantLock
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;
public class Traps {
public static void main(String[] args) throws InterruptedException {
StampedLock lock = new StampedLock();
// 1. Not reentrant: the write lock holder cannot lock again
long w = lock.writeLock();
System.out.println("1. tryWriteLock while holding it: " + lock.tryWriteLock());
System.out.println("1. tryReadLock(200 ms) while holding write: "
+ lock.tryReadLock(200, TimeUnit.MILLISECONDS) + " (readLock() would hang)");
lock.unlockWrite(w);
// 2. A wrong or stale stamp is rejected
long r = lock.readLock();
try {
lock.unlockWrite(r);
} catch (IllegalMonitorStateException e) {
System.out.println("2. unlockWrite with a read stamp: IllegalMonitorStateException");
}
lock.unlockRead(r);
try {
lock.unlockRead(r);
} catch (IllegalMonitorStateException e) {
System.out.println("2. unlocking the same stamp twice: IllegalMonitorStateException");
}
// 3. No owner: any thread holding the stamp can unlock
long stamp = lock.writeLock();
Thread other = new Thread(() -> lock.unlockWrite(stamp));
other.start();
other.join();
System.out.println("3. unlocked by another thread, isWriteLocked: " + lock.isWriteLocked());
// 4. No Conditions; asReadLock/asWriteLock give plain Lock views without them
try {
lock.asWriteLock().newCondition();
} catch (UnsupportedOperationException e) {
System.out.println("4. asWriteLock().newCondition(): UnsupportedOperationException");
}
}
}
Output:
1. tryWriteLock while holding it: 0
1. tryReadLock(200 ms) while holding write: 0 (readLock() would hang)
2. unlockWrite with a read stamp: IllegalMonitorStateException
2. unlocking the same stamp twice: IllegalMonitorStateException
3. unlocked by another thread, isWriteLocked: false
4. asWriteLock().newCondition(): UnsupportedOperationException
- A thread holding the write lock could not lock again:
returned 0, and even a read lock timed out after 200 ms. With the blockingtryWriteLock() , the thread would have deadlocked with itself. Code that calls another method which also locks, such as a public method calling another public method, must be restructured, because the hold count that saves you withreadLock() does not exist.ReentrantLock - Unlocking with the wrong kind of stamp, or the same stamp twice, throws
. The lock checks stamps, not threads.IllegalMonitorStateException - Another thread released the write lock using the stamp, and that was accepted:
became false. That can be useful for handing a locked state between threads, but it means a stamp leaked to the wrong code can unlock the data.isWriteLocked - The
andasWriteLock() views implement the plainasReadLock() interface for APIs that need one, butLock throwsnewCondition() . A thread that must wait for a state change needs a different lock.UnsupportedOperationException
Also, the non-interruptible readLock()writeLock()...InterruptiblyStampedLock
How much optimistic reads save
Two reader threads each read two fields 2 million times, first with no writer and then with a writer that updates the fields every millisecond. Each lock runs 3 times and the fastest run is reported. This is a rough comparison on a 2-CPU machine, not a benchmark.
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;
import java.util.function.LongSupplier;
public class ReadHeavyBenchmark {
static long a;
static long b;
static final ReentrantReadWriteLock RW = new ReentrantReadWriteLock();
static final StampedLock SL = new StampedLock();
static long readRw() {
RW.readLock().lock();
try {
return a + b;
} finally {
RW.readLock().unlock();
}
}
static long readStampedLock() {
long s = SL.readLock();
try {
return a + b;
} finally {
SL.unlockRead(s);
}
}
static long readOptimistic() {
long stamp = SL.tryOptimisticRead();
long sum = a + b;
if (!SL.validate(stamp)) {
stamp = SL.readLock();
try {
sum = a + b;
} finally {
SL.unlockRead(stamp);
}
}
return sum;
}
static volatile long sink;
public static void main(String[] args) throws InterruptedException {
int perThread = 2000000;
for (boolean writer : new boolean[] {false, true}) {
System.out.println("2 reader threads x 2,000,000 reads, "
+ (writer ? "1 writer every 1 ms" : "no writer") + ", best of 3:");
time("ReentrantReadWriteLock", ReadHeavyBenchmark::readRw, perThread, writer);
time("StampedLock readLock", ReadHeavyBenchmark::readStampedLock, perThread, writer);
time("StampedLock optimistic", ReadHeavyBenchmark::readOptimistic, perThread, writer);
}
}
static void time(String name, LongSupplier read, int perThread, boolean withWriter)
throws InterruptedException {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
AtomicBoolean stop = new AtomicBoolean();
Thread writer = new Thread(() -> {
while (withWriter && !stop.get()) {
if (name.startsWith("Reentrant")) {
RW.writeLock().lock();
a++;
b--;
RW.writeLock().unlock();
} else {
long s = SL.writeLock();
a++;
b--;
SL.unlockWrite(s);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
return;
}
}
});
writer.start();
Thread[] readers = new Thread[2];
long t0 = System.nanoTime();
for (int i = 0; i < readers.length; i++) {
readers[i] = new Thread(() -> {
long sum = 0;
for (int k = 0; k < perThread; k++) {
sum += read.getAsLong();
}
sink = sum;
});
readers[i].start();
}
for (Thread t : readers) {
t.join();
}
best = Math.min(best, System.nanoTime() - t0);
stop.set(true);
writer.join();
}
System.out.printf(" %-24s %,6d ms%n", name, best / 1000000);
}
}
Output (rough timings, 2-CPU Linux machine, JDK 21):
2 reader threads x 2,000,000 reads, no writer, best of 3:
ReentrantReadWriteLock 170 ms
StampedLock readLock 367 ms
StampedLock optimistic 4 ms
2 reader threads x 2,000,000 reads, 1 writer every 1 ms, best of 3:
ReentrantReadWriteLock 295 ms
StampedLock readLock 221 ms
StampedLock optimistic 5 ms
- Optimistic reads were tens of times faster than either kind of read lock, with or without the writer. Each optimistic read is two plain field reads, a version check and a fence, with no write to shared memory.
- The
read lock and theReentrantReadWriteLock read lock were within about two times of each other, and which one came out ahead varied between runs. Both update a shared reader count on every acquire and release, so the two reader threads keep pulling the same cache line from each other's core.StampedLock - A writer every millisecond made little difference to the optimistic readers, because a write invalidates only the reads that overlap it, and those then fall back to a read lock. With very frequent writes, many optimistic reads would fail and the advantage would shrink.
Choosing between StampedLock and the alternatives
| Situation | Use |
|---|---|
| A few fields read very often, written rarely | StampedLock |
| Long reads, rare writes, code that calls back into the class | |
| Threads must wait for a state change | ReentrantLockCondition |
| The data can be an immutable object | A volatileAtomicReference |
| A single number or reference | |
| A map read by many threads | |
| Simple, low-contention mutual exclusion |
Keep the optimistic pattern in one small, private method per class, written exactly in the form shown here: stamp, copy to locals, validate, fall back. The Javadoc of StampedLock