Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java StampedLock optimistic reads: validate before publishing state

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A StampedLock optimistic read observes fields without holding a read lock, so the observation must be validated before it becomes a result.

Treat the stamp as a version check

Copy only the primitive fields or safe references needed for the decision, then call validate. A writer can change several related fields between reads. If validation fails, retry under a read lock. The fixture forces a write between observation and validation so the failed path is visible without relying on scheduler timing.

This is not a substitute for a transaction across unrelated objects. Basic lock ownership is easier to reason about when reads are not extremely frequent; read-write lock downgrading covers a different transition.

Keep locked sections small

StampedLock is not reentrant. Calling an unknown method while holding one of its locks can deadlock if that method tries to acquire the same lock. For mutable object graphs, a validated primitive stamp does not prove every dereference was safe; copy a stable snapshot under a read lock instead.

Working program

Java
import java.util.concurrent.locks.StampedLock;

public class WarehouseStockSnapshot {
    public static void main(String[] args) {
        StampedLock guard = new StampedLock();
        int[] stock = {47};
        long optimistic = guard.tryOptimisticRead();
        int tentative = stock[0];
        long writer = guard.writeLock();
        try { stock[0] = 82; }
        finally { guard.unlockWrite(writer); }
        System.out.println("tentative=" + tentative);
        System.out.println("valid=" + guard.validate(optimistic));
        long reader = guard.readLock();
        try { System.out.println("current=" + stock[0]); }
        finally { guard.unlockRead(reader); }
    }
}

Output

Output
tentative=47
valid=false
current=82

Cost and ownership

The optimistic attempt avoids read-lock acquisition when no writer intervenes; this fixture deliberately pays for a fallback read lock. Both paths use constant storage. Under frequent writes, failed retries may cost more than ordinary locking, so measure the actual workload.

Common Mistakes

  • Do not return tentative fields before validate succeeds.
  • Do not treat an optimistic stamp as a held lock.
  • Do not call reentrant code while holding a StampedLock mode.

Read next

Java ReentrantLock: protect a complete state transition, readwritelock downgrade, Java atomic variables: compare-and-set and one-variable invariants, Java concurrency reference: admission, visibility, atomicity and completion.

java
concurrency
stampedlock-optimistic-read
Storage details