java / expert
Snippet
Optimistic Locking with StampedLock
StampedLock offers an 'optimistic' mode where no actual lock is acquired. Instead, it returns a stamp that must be validated later. If a write occurred during the read, the validation fails and the code falls back to a traditional read lock. This significantly reduces contention in read-heavy systems.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
long stamp = lock.tryOptimisticRead();int currentX = x, currentY = y;if (!lock.validate(stamp)) {stamp = lock.readLock();try {currentX = x; currentY = y;} finally {lock.unlockRead(stamp);}}return Math.sqrt(currentX * currentX + currentY * currentY);
Breakdown
1
lock.tryOptimisticRead()
Attempts a non-blocking read without actually locking the resource.
2
lock.validate(stamp)
Checks if the lock was acquired by a write thread since the stamp was issued.
3
lock.readLock()
The fallback path that acquires a full pessimistic read lock if validation failed.