Skip to main content
  1. Java Concurrency (java.util.concurrent)/

StampedLock

1 min

StampedLock is a specialized lock that provides three different modes for read/write access. It is often faster than ReentrantReadWriteLock for read-heavy workloads.

Source Code #

View Source on GitHub

The “Optimistic Read” Mode #

Unlike ReentrantReadWriteLock, StampedLock provides an optimistic read mode.

  1. Get a Stamp: Call tryOptimisticRead() to get a version stamp.
  2. Read the Fields: Copy the fields you need into local variables.
  3. Validate: Call validate(stamp) to check for writer interference.
long stamp = sl.tryOptimisticRead(); // Not a real lock!
int x = this.x, y = this.y; // Read state
if (!sl.validate(stamp)) { // Check for writer interference
    stamp = sl.readLock(); // Validation failed, upgrade to pessimistic lock
    try { x = this.x; y = this.y; } finally { sl.unlockRead(stamp); }
}
return Math.sqrt(x*x + y*y);

Canonical Usage #

When to use: Use StampedLock when you have read-heavy data structures where the read-only sections are short and infrequent updates are expected.

Common Patterns:

  • Upgrade Pattern: Using tryConvertToWriteLock to upgrade from a read lock to a write lock atomically.
  • Optimistic Reading: Using tryOptimisticRead as the first choice.

Resilience and Safety #

  • Non-Reentrant: StampedLock is not reentrant.
  • No Monitor Support: StampedLock does not support Condition objects.