Java 并发:CAS 与锁定 [英] Java Concurrency: CAS vs Locking

查看:21
本文介绍了Java 并发:CAS 与锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java 并发实践这本书.在第 15 章中,他们讨论了非阻塞算法和 compare-and-swap (CAS) 方法.

I'm reading the Book Java Concurrency in Practice. In chapter 15, they are talking about the nonblocking algorithms and the compare-and-swap (CAS) method.

据说 CAS 的性能比锁定方法好得多.我想问那些已经使用过这两个概念并且想听听您何时更喜欢这些概念中的哪一个的人?真的有这么快吗?

It is written that CAS perform much better than the locking methods. I want to ask the people who already worked with both of these concepts and would like to hear when you are preferring which one of these concepts? Is it really so much faster?

对我来说,锁的用法更清晰易懂,甚至更好维护(如果我错了,请纠正我).我们真的应该专注于创建与 CAS 相关的并发代码而不是锁以获得更好的性能提升还是可持续性更重要?

For me, the usage of locks is much clearer and easier to understand and maybe even better to maintain (please correct me if I am wrong). Should we really focus on creating our concurrent code related to CAS than locks to get a better performance boost or is sustainability more important?

我知道可能没有严格的规定何时使用什么.但我只是想听听关于CAS新概念的一些意见和经验.

I know there is maybe not a strict rule when to use what. But I just would like to hear some opinions, experiences with the new concept of CAS.

推荐答案

CAS 通常比锁定快得多,但它确实取决于争用的程度.因为如果值在读取和比较之间发生变化,CAS 可能会强制重试,如果相关变量受到许多其他线程的重击(或者如果计算新值的成本很高),则理论上线程可能会陷入忙等待来自旧值(或两者)).

CAS is generally much faster than locking, but it does depend on the degree of contention. Because CAS may force a retry if the value changes between reading and comparing, a thread can theoretically get stuck in a busy-wait if the variable in question is being hit hard by many other threads (or if it is expensive to compute a new value from the old value (or both)).

CAS 的主要问题是正确编程比锁定要困难得多.请注意,反过来,锁定比消息传递或 STM 更难正确使用,所以不要把这当作对使用锁的响亮的认可.

The main issue with CAS is that it is much more difficult to program with correctly than locking. Mind you, locking is, in turn, much harder to use correctly than message-passing or STM, so don't take this as a ringing endorsement for the use of locks.

这篇关于Java 并发:CAS 与锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆