简体   繁体   English

ReadWriteLock与StampedLock

[英]ReadWriteLock vs StampedLock

I've been using ReadWriteLock `s to implement/maintain a locking idioms. 我一直在使用ReadWriteLock来实现/维护锁定习惯用法。

Since JDK8 StampedLock has been introduced. 从JDK8开始, StampedLock被引入。 And as RWLocks are known with their slowness and bad performance, StampedLock's look like an alternative (they are not reentrant, so much faster). 而且由于RWLocks的缓慢性和不良性能而闻名,StampedLock看起来像是一种替代品(它们不是可重入的,所以速度更快)。

However except the performance, it looks to me that StampedLock's are much harder and complex to maintain and use - eg threads can now deadlock against themselves - so corresponding actions should be taken. 但是,除了性能之外,在我看来,StampedLock的维护和使用起来更加困难和复杂-例如,线程现在可以对自己进行死锁-因此应采取相应的措施。

What are the benefits of StampedLock over RWLock ? StampedLock相对RWLock有什么好处?

This article explains the differences in detail. 本文详细解释了差异。

The ReentrantReadWriteLock had a lot of shortcomings: It suffered from starvation. ReentrantReadWriteLock有很多缺点:遭受了饥饿。 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. Doug Lea的新Java 8 StampedLock解决了所有这些缺点。 With some clever code idioms we can also get better performance. 通过一些巧妙的代码习惯用法,我们还可以获得更好的性能。

Well, yes ReentrantReadWriteLock had problems (when compared to the traditional synchronized block) in 5.0 but they fixed it in java 6.0. 好吧,是的,ReentrantReadWriteLock在5.0中有问题(与传统的同步块相比),但在Java 6.0中已解决。

So, if you guys use Java 6 in production, you can use the lock API with confidence. 因此,如果您在生产中使用Java 6,则可以放心使用lock API。

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. 锁API的好处是它使用CAS /非阻塞,因此除非您忘记在finally块中解锁它,否则它永远不会死锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM