StampedLock for Optimistic Locking in Java


StampedLock supports both read and write locks, including optimistic read locks, offering better throughput under high contention.

Source Code

StampedLock lock = new StampedLock();
long stamp = lock.tryOptimisticRead();
try {
    // perform read operations
    if (!lock.validate(stamp)) {
        stamp = lock.readLock(); // Fallback to read lock
        try {
            // re-read data
        } finally {
            lock.unlockRead(stamp);
        }
    }
} finally {
    lock.unlock(stamp);
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments