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

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

问题描述

目前正在阅读本书 Java Concurrency in Practice 。在第15章中,他们谈到非阻塞算法和比较和交换(CAS)方法。

Im currently reading the Book Java Concurrency in Practice. In the Chapter 15 they are speaking about the Nonblocking algorithms and the compare-and-swap (CAS) Method.

它的写法是CAS执行比锁定方法好多了。 我想询问已经使用这两个概念的人,并希望听到您喜欢这些概念中的哪一个?

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

我知道也许没有一个严格的规则,什么时候使用什么。 但我只想听听一些关于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 vs锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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