Java Concurrency Interview

Locks, conditions and AQS question 38 of 180 senior

What is optimistic reading in StampedLock?

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.

locks stampedlock

Quiz yourself on Locks, conditions and AQS Suggest a correction