intermediateConcurrency Utilities

What is StampedLock, and when should you prefer it over ReadWriteLock?

StampedLock supports three distinct modes of access. A write lock is fully exclusive, just like ReadWriteLock's write lock. A read lock is shared and allows multiple concurrent readers, also like ReadWriteLock's read lock. The third mode, optimistic read, is unique to StampedLock: calling tryOptimisticRead() returns a stamp immediately without acquiring any actual lock at all. The caller reads the data it needs and then calls validate(stamp); if no write occurred in the meantime, the stamp is still valid and the read was consistent, and if validation fails, the code falls back to acquiring a genuine read lock and trying again. StampedLock is the better choice when reads are extremely frequent and contention with writers is rare, because the optimistic-read path avoids acquiring any lock at all in the common case, making it faster than ReadWriteLock. The important caveat is that StampedLock is not reentrant: a thread that already holds the write lock and then tries to also acquire the read lock on the same instance will deadlock itself.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What are ConcurrentHashMap's compute methods, and why should you prefer them over a separate get and put?← Back to all Java Concurrency & Multithreading questions