StampedLock Optimistic Read
Take an optimistic snapshot with tryOptimisticRead and validate the stamp; fall back to a real read lock only when a write interfered mid-read.
Code
import java.util.concurrent.locks.StampedLock;
public class PositionTracker {
private final StampedLock lock = new StampedLock();
private double x;
private double y;
void move(double deltaX, double deltaY) {
long stamp = lock.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
lock.unlock(stamp);
}
}
double distanceFromOrigin() {
long stamp = lock.tryOptimisticRead(); // 乐观读:不阻塞写者
double currentX = x;
double currentY = y;
if (!lock.validate(stamp)) { // 读期间发生写入:快照作废
stamp = lock.readLock(); // 降级为完整读锁重读
try {
currentX = x;
currentY = y;
} finally {
lock.unlock(stamp);
}
}
return Math.hypot(currentX, currentY);
}
public static void main(String[] args) {
PositionTracker tracker = new PositionTracker();
tracker.move(3, 4);
tracker.move(1, -2);
System.out.println("distance = " + tracker.distanceFromOrigin());
}
}What the code does
StampedLock Optimistic Read keeps everything in the class PositionTracker and the function main.
Using it
The demo output is labeled (distance =), so every printed line maps back to its originating operation.
Key statements
return Math.hypot(currentX, currentY);
x += deltaX;
y += deltaY;
Interactive Tools for This Topic
FAQ
- What does StampedLock Optimistic Read print when run?
- Execute the whole file; each printed line is prefixed with a label like `distance =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.