Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadWriteLock vs StampedLock

I've been using ReadWriteLock`s to implement/maintain a locking idioms.

Since JDK8 StampedLock has been introduced. And as RWLocks are known with their slowness and bad performance, StampedLock's look like an alternative (they are not reentrant, so much faster).

However except the performance, it looks to me that StampedLock's are much harder and complex to maintain and use - e.g. threads can now deadlock against themselves - so corresponding actions should be taken.

What are the benefits of StampedLock over RWLock ?

like image 683
vtor Avatar asked Mar 07 '15 17:03

vtor


People also ask

What is Stampedlock?

StampedLocks are designed for use as internal utilities in the development of thread-safe components. Their use relies on knowledge of the internal properties of the data, objects, and methods they are protecting.

What is ReadWriteLock in Java?

A ReadWriteLock maintains a pair of associated locks , one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

Why locks are better than synchronized?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code.


2 Answers

This article explains the differences in detail.

The ReentrantReadWriteLock had a lot of shortcomings: It suffered from starvation. You could not upgrade a read lock into a write lock. There was no support for optimistic reads. Programmers "in the know" mostly avoided using them.

Doug Lea's new Java 8 StampedLock addresses all these shortcomings. With some clever code idioms we can also get better performance.

like image 86
lbalazscs Avatar answered Sep 22 '22 11:09

lbalazscs


Well, yes ReentrantReadWriteLock had problems (when compared to the traditional synchronized block) in 5.0 but they fixed it in java 6.0.

So, if you guys use Java 6 in production, you can use the lock API with confidence.

Performance wise lock & traditional synchronization gives you same.

The good thing about lock API is that it uses CAS/non-blocking so it will never end up with deadlock unless you forget to unlock it in the finally block.

like image 45
gowtham paruchuri Avatar answered Sep 18 '22 11:09

gowtham paruchuri