Recently I learned about the existence StampedLock
?
https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/locks/StampedLock.html I realized that It is improved ReentrantReadWriteLock with some differernces:
- Is not reentrant
- Supports optimistic lock
- Supports upgrade from readLock to writeLock
Also I read examples frpm javadoc but I don't understant that code:
class Point {
private double x, y;
private final StampedLock sl = new StampedLock();
// a read-only method
// upgrade from optimistic read to read lock
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead();
try {
retryHoldingLock: for (;; stamp = sl.readLock()) {
if (stamp == 0L)
continue retryHoldingLock;
// possibly racy reads
double currentX = x;
double currentY = y;
if (!sl.validate(stamp))
continue retryHoldingLock;
return Math.hypot(currentX, currentY);
}
} finally {
if (StampedLock.isReadLockStamp(stamp))
sl.unlockRead(stamp);
}
}
}
What does it mean possibly racy reads
? [ANSWERRED IN COMMENTS]
Is it a problem if another thread reads x
or y
? [ANSWERRED IN COMMENTS]
why do we execute tryOptimisticRead first and readLock in the for loop in case of tryOptimisticRead failure? what the logic?
Why do we have if (StampedLock.isReadLockStamp(stamp))
inside finally block vbefore unlock ?