StampedLock and Optimistic Reads
Apply StampedLock's optimistic read mode for high-throughput, read-dominant workloads.
StampedLock and Optimistic Reads is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is StampedLock?
Introduced in Java 8, StampedLock extends ReadWriteLock concepts with an additional optimistic read mode. Operations return a long stamp used to release the lock or validate the optimistic read.
import java.util.concurrent.locks.*;
StampedLock sl = new StampedLock();
// Exclusive write:
long stamp = sl.writeLock();
try {
// write data
} finally {
sl.unlockWrite(stamp);
}
// Shared read:
stamp = sl.readLock();
try {
// read data
} finally {
sl.unlockRead(stamp);
}Optimistic Read Mode
Optimistic read acquires no lock — it just gets a stamp. After reading, validate the stamp. If validation fails (a writer intervened), fall back to a real read lock:
StampedLock sl2 = new StampedLock();
double x = 0, y = 0;
// Try optimistic read first:
long stamp = sl2.tryOptimisticRead();
double localX = x, localY = y; // read values
if (!sl2.validate(stamp)) {
// A write occurred — fall back to read lock
stamp = sl2.readLock();
try {
localX = x;
localY = y;
} finally {
sl2.unlockRead(stamp);
}
}
// use localX and localYFull Point2D Example
Classic StampedLock example — a 2D point with optimistic reads:
class Point {
private double x, y;
private final StampedLock lock = new StampedLock();
void move(double dx, double dy) {
long stamp = lock.writeLock();
try { x += dx; y += dy; }
finally { lock.unlockWrite(stamp); }
}
double distanceFromOrigin() {
long stamp = lock.tryOptimisticRead();
double cx = x, cy = y;
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try { cx = x; cy = y; }
finally { lock.unlockRead(stamp); }
}
return Math.sqrt(cx * cx + cy * cy);
}
}Lock Conversion
StampedLock supports converting between lock modes:
StampedLock sl3 = new StampedLock();
// Read → Write upgrade attempt:
long readStamp = sl3.readLock();
long writeStamp = sl3.tryConvertToWriteLock(readStamp);
if (writeStamp != 0) {
// Successfully upgraded!
// ... write ...
sl3.unlockWrite(writeStamp);
} else {
// Upgrade failed — release read and reacquire write
sl3.unlockRead(readStamp);
writeStamp = sl3.writeLock();
// ... write ...
sl3.unlockWrite(writeStamp);
}When Optimistic Reads Help Most
Optimistic reads shine when:
- Reads are vastly more frequent than writes
- The data snapshot fits in a few local variables (no object allocation)
- Write contention is low (validation rarely fails)
If writes are frequent, optimistic reads fall back to full read locks repeatedly — providing no benefit.
StampedLock vs ReadWriteLock
Key differences:
- StampedLock: adds optimistic reads; NOT reentrant; no Condition support
- ReentrantReadWriteLock: reentrant; supports Conditions; no optimistic mode
StampedLock is faster under low write contention. ReentrantReadWriteLock is safer and more feature-rich.
StampedLock is NOT Reentrant
Unlike ReentrantLock, StampedLock is NOT reentrant. A thread trying to acquire a mode it already holds will deadlock:
StampedLock sl4 = new StampedLock();
long s1 = sl4.readLock();
// DO NOT: sl4.readLock() again — deadlocks with non-reentrant!tryWriteLock and tryReadLock
Non-blocking acquisition attempts return 0 if unsuccessful:
StampedLock sl5 = new StampedLock();
long stamp = sl5.tryWriteLock();
if (stamp != 0) {
try {
System.out.println("Got write lock");
} finally {
sl5.unlockWrite(stamp);
}
} else {
System.out.println("Write lock unavailable");
}Using as ReadWriteLock
StampedLock can return a view as a standard ReadWriteLock for compatibility:
StampedLock sl6 = new StampedLock();
Lock readLock = sl6.asReadLock();
Lock writeLock = sl6.asWriteLock();
ReadWriteLock rwView = sl6.asReadWriteLock();
// These provide standard Lock interface without optimistic modePerformance Benchmark Intuition
Benchmark results typically show:
- Very read-heavy (99% reads): StampedLock > ReadWriteLock > synchronized
- Mixed workload (70% reads): ReadWriteLock ≈ StampedLock
- Write-heavy: synchronized or ReentrantLock often wins (less overhead)
Always profile with realistic workloads before optimizing.
Stamp Invalidity After Unlock
After releasing a lock with a stamp, that stamp becomes invalid. Using an old stamp after unlock leads to undefined behavior — always capture a fresh stamp per lock acquisition.
StampedLock sl7 = new StampedLock();
long stamp = sl7.writeLock();
sl7.unlockWrite(stamp);
// stamp is now invalid — don't use it:
// sl7.unlockWrite(stamp); // throws IllegalMonitorStateException or corrupts stateQuick Check
An optimistic read with tryOptimisticRead() and a subsequent validate(stamp) returns false. What should the code do next?
Recap: StampedLock
Key takeaways:
- Three modes: optimistic read (no lock), read lock, write lock
- tryOptimisticRead() + validate() — zero-cost read attempt
- On validation failure → fall back to readLock()
- NOT reentrant — deadlock risk if same thread re-acquires
- No Condition support — use ReentrantReadWriteLock when needed
Frequently asked questions
Is the “StampedLock and Optimistic Reads” lesson free?
Yes — the full text of “StampedLock and Optimistic Reads” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “StampedLock and Optimistic Reads”?
Apply StampedLock's optimistic read mode for high-throughput, read-dominant workloads. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “StampedLock and Optimistic Reads” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- ReentrantLock vs synchronized
- ReadWriteLock for Reader-Writer Scenarios
- Atomic Variables: Lock-Free Updates
- StampedLock and Optimistic Reads