Locks, conditions and AQS question 38 of 180 senior
What is optimistic reading in StampedLock?
- A read that retries until it succeeds
- Correct: A read that takes no lock at all, then validates a stamp afterwards and falls back to a real read lock if a writer intervened
- A read that blocks writers
- Another name for a read lock
tryOptimisticRead() returns a stamp without acquiring anything: no CAS, no write to shared state, so
no cache-line ping-pong between readers. You copy the fields you need, then call validate(stamp). If
a writer took the lock in the meantime, validation fails and you fall back to readLock().
long stamp = lock.tryOptimisticRead();
double currentX = x, currentY = y; // may be an inconsistent snapshot
if (!lock.validate(stamp)) { // so it must be validated
stamp = lock.readLock();
try { currentX = x; currentY = y; } finally { lock.unlockRead(stamp); }
}
The rules that go with it: the values you read before validating may be torn, so do not act on them
until validation passes; StampedLock is not reentrant, so recursion deadlocks; and it has no
Condition support.
Quiz yourself on Locks, conditions and AQS Suggest a correction