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 #
The “Optimistic Read” Mode #
Unlike ReentrantReadWriteLock, StampedLock provides an optimistic read mode.
- Get a Stamp: Call
tryOptimisticRead()to get a version stamp. - Read the Fields: Copy the fields you need into local variables.
- 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
tryConvertToWriteLockto upgrade from a read lock to a write lock atomically. - Optimistic Reading: Using
tryOptimisticReadas the first choice.
Resilience and Safety #
- Non-Reentrant:
StampedLockis not reentrant. - No Monitor Support:
StampedLockdoes not supportConditionobjects.