Search code examples
javamultithreadingjava-8locking

What is StampedLock in Java?


I am working on a Java code, I need to implement threading in it. I was going through JAVA 8 API and I come to know about Stamped Locks. Can anyone tell me why to use StampedLocks in multithreading?


Solution

  • StampedLock is an alternative to using a ReadWriteLock (implemented by ReentrantReadWriteLock). The main differences between StampedLock and ReentrantReadWriteLock are that:

    • StampedLocks allow optimistic locking for read operations
    • ReentrantLocks are reentrant (StampedLocks are not)

    So if you have a scenario where you have contention (otherwise you may as well use synchronized or a simple Lock) and more readers than writers, using a StampedLock can significantly improve performance.

    However you should measure the performance based on your specific use case before jumping to conclusions.

    Heinz Kabutz has written about StampedLocks in his newsletter and he also made a presentation about performance.