Video in progress
How does StampedLock's optimistic read mode work, and what are its dangers?
tryOptimisticRead() takes no lock and only returns a "stamp". After reading, validate(stamp) checks that no write happened in between; if one did, you re-read with a regular read lock. It is fast, but not reentrant and easy to misuse.
📖 Answer
class Point {
private double x, y;
private final StampedLock sl = new StampedLock();
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead();
double cx = x, cy = y; // we read into local copies
if (!sl.validate(stamp)) { // did a write happen in between?
stamp = sl.readLock();
try {
cx = x; cy = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.hypot(cx, cy);
}
void move(double dx, double dy) {
long stamp = sl.writeLock();
try { x += dx; y += dy; } finally { sl.unlockWrite(stamp); }
}
}
In an optimistic read no shared counter is updated, so on a many-core machine it is much faster than ReentrantReadWriteLock.
The dangers:
- values read before
validatecan be inconsistent. Don't base anything on them: using them as an index or dereferencing an object inside can give you anArrayIndexOutOfBoundsor an NPE. Copy only primitives into locals, validate, and only then use them; - it is not reentrant: if a thread holding the write lock requests
writeLock()again, it blocks itself; - there is no
Condition; readLock()/writeLock()don't respond to interrupts (there are...Interruptiblyvariants).
I use it only in "hot" spots with simple, small state that a profiler has clearly pointed to.
Sign up to mark studied questions and save your progress.