Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Thanks in advance.

like image 397
Mohit Avatar asked Sep 29 '14 07:09

Mohit


1 Answers

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.

like image 63
assylias Avatar answered Oct 20 '22 23:10

assylias