Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the difference between StampedLock and ReadWriteLock?
| ReentrantReadWriteLock | StampedLock |
| Read lock and write lock, both truly acquired and held. | Adds a third mode: optimistic read, which takes no lock at all. |
| Reentrant: a thread can re-acquire a lock it already holds. | Not reentrant; re-acquiring the same stamp-based lock from the same thread can deadlock. |
| Readers can starve writers, or vice versa, depending on fairness settings. | Optimistic reads never block writers at all, since they don't take a lock. |
| Supports Condition objects for wait/signal style coordination. | No Condition support. |
StampedLock's optimistic read mode works by returning a stamp, letting the reader proceed without blocking, and then requiring the reader to call validate(stamp) afterward to check whether a write occurred in the meantime; if it did, the reader must fall back to a full read lock and retry.
long stamp = lock.tryOptimisticRead(); int localX = x, localY = y; // read fields optimistically, no lock taken if (!lock.validate(stamp)) { // a write happened concurrently, retry safely stamp = lock.readLock(); try { localX = x; localY = y; } finally { lock.unlockRead(stamp); } }
This makes StampedLock faster than ReentrantReadWriteLock for read-heavy, low-conflict workloads, at the cost of a less familiar API, no reentrancy, and the extra responsibility of writing correct validate-and-retry logic.
More Related questions...