Multithreading: StampedLock's optimistic read skips locking

tryOptimisticRead() returns a stamp without blocking anyone, and validate() checks afterwards whether a writer slipped in while the read happened. When nothing changed, the optimistic read is used as-is and no real lock is ever taken.

Code
StampedLock lock = new StampedLock();
int[] point = { 3, 4 };
long stamp = lock.tryOptimisticRead();
int x = point[0];
int y = point[1];
if (!lock.validate(stamp)) {
    stamp = lock.readLock();
    try {
        x = point[0];
        y = point[1];
    } finally {
        lock.unlockRead(stamp);
    }
}
System.out.println("Point read optimistically: (" + x + ", " + y + ")");
Output
Point read optimistically: (3, 4)
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms