CKTIS / Java
StampedLock: optimistic reads, writes, and read-lock fallback
Learn when an optimistic read can be trusted and how to retry under a shared read lock using the correct stamp to release it.
Version: Java SE 21
Syntax
java.util.concurrent.locks.StampedLock — Java SE 21
public long tryOptimisticRead()
public boolean validate(long stamp)
public long writeLock()
public void unlockWrite(long stamp)
public long readLock()
public void unlockRead(long stamp)In Java SE 21, java.util.concurrent.locks.StampedLock supports exclusive writes, shared reads, and optimistic reads. The method group StampedLock.tryOptimisticRead/validate/writeLock/unlockWrite/readLock/unlockRead covers starting and validating an optimistic read, acquiring and releasing a write lock, and acquiring and releasing a read lock. tryOptimisticRead() does not wait or hold a lock: it returns a long stamp, or 0L if a write lock is already held. There is nothing to unlock for an optimistic stamp.
With a nonzero stamp, copy the needed fields into local variables, then call validate(long) on the same lock. For a fresh optimistic stamp, true means no write lock was acquired since the stamp was issued. It does not protect against a later write. validate(0L) always returns false. Before successful validation, the copies may be inconsistent: do not use them in calls or actions that assume consistency. If validation returns false, discard all the copies.
writeLock() acquires the lock exclusively and waits if necessary. Acquisition itself invalidates earlier optimistic stamps, even if nothing is changed and even after the writer releases the lock. Update protected data under the write lock and pass its stamp to unlockWrite(long) in finally.
After a zero stamp or failed validation, use readLock() to acquire a shared lock, waiting if necessary. Reread every needed field, then call unlockRead(long) in finally with the stamp returned by readLock(), not the optimistic stamp. The unlock methods throw IllegalMonitorStateException if the stamp does not match the lock state. The lock is not reentrant; do not try to reacquire it while already holding it. Stamps are not security credentials.
Examples
import java.util.concurrent.locks.StampedLock;
public class StampedLockDemo {
private final StampedLock lock = new StampedLock();
private int value = 10;
private void write(int newValue) {
long writeStamp = lock.writeLock();
try {
value = newValue;
} finally {
lock.unlockWrite(writeStamp);
}
}
private void demo() {
long firstStamp = lock.tryOptimisticRead();
int firstCopy = value;
boolean firstValid = lock.validate(firstStamp);
System.out.println("first valid: " + firstValid);
if (firstValid) {
System.out.println("first value: " + firstCopy);
}
long secondStamp = lock.tryOptimisticRead();
int secondCopy = value;
write(20);
boolean secondValid = lock.validate(secondStamp);
System.out.println("second valid: " + secondValid);
if (!secondValid) {
long readStamp = lock.readLock();
try {
secondCopy = value;
} finally {
lock.unlockRead(readStamp);
}
}
System.out.println("second value: " + secondCopy);
}
public static void main(String[] args) {
new StampedLockDemo().demo();
}
}Result
first valid: true first value: 10 second valid: false second value: 20
The demo uses one thread. The first read validates and yields `10`. On the second read, the write of `20` is deliberately placed between copying the field and validating the stamp. The stale copy is replaced with `20`, read under a lock that is released using `readStamp`.
Related lessons
- Java · Lesson 29 · Advanced · Version: 2