StampedLock Try Convert Write Lock
After an optimistic snapshot fails validation, take a read lock and let tryConvertToWriteLock upgrade it to a write stamp in one uncontended step.
Code
import java.util.concurrent.locks.StampedLock;
public class OptimisticUpgrade {
private static final StampedLock LOCK = new StampedLock();
public static void main(String[] args) {
// 乐观读:不阻塞写者,只拿一个快照戳
long optimistic = LOCK.tryOptimisticRead();
System.out.println("fresh snapshot valid: " + LOCK.validate(optimistic));
// 模拟干扰:写者持有写锁改数据,旧快照随之过期
long writeStamp = LOCK.writeLock();
System.out.println("stale snapshot valid: " + LOCK.validate(optimistic));
// 锁被写者持有,无法升级,返回 0
System.out.println("stale converts: " + (LOCK.tryConvertToWriteLock(optimistic) != 0));
LOCK.unlockWrite(writeStamp);
// 经典升级路径:validate 失败后取读锁,再尝试升级为写锁
long readStamp = LOCK.readLock();
long upgraded = LOCK.tryConvertToWriteLock(readStamp);
if (upgraded != 0L) {
// 无写者竞争:一次调用释放读锁并直接拿到写戳
System.out.println("upgraded read -> write");
LOCK.unlockWrite(upgraded);
} else {
// 升级失败:先放读锁,再完整取写锁
System.out.println("upgrade failed, release and re-take");
LOCK.unlockRead(readStamp);
}
}
}Inside the snippet
Under the hood: the class OptimisticUpgrade and the function main.
Watch out for
- Copy, run: the standard library answers every call in the file.
Putting it to use
Entry signature: public static void main(String[] args)
Look for the fresh snapshot valid:, stale snapshot valid:, stale converts: prefixes when the file runs; they tie each line to its step.
The core lines of the flow
long upgraded = LOCK.tryConvertToWriteLock(readStamp);
long optimistic = LOCK.tryOptimisticRead();
long writeStamp = LOCK.writeLock();
Interactive Tools for This Topic
FAQ
- What does StampedLock Try Convert Write Lock print when run?
- Running the file directly is enough — expect labeled output lines such as `fresh snapshot valid:`, `stale snapshot valid:`, `stale converts:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.