一千萬個為什麽

搜索

Java並發:CAS與鎖定

我正在閱讀Book Java Concurrency in Practice 。在第15章中,他們討論了非阻塞算法和比較和交換(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相關的並發代碼而不是鎖定以獲得更好的性能提升或者可持續性更重要?

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的主要問題是正確編程比鎖定要困難得多。請註意,鎖定反過來比消息傳遞或 STM 更難正確使用,所以不要把它當作使用鎖的響聲代言。

轉載註明原文: Java並發:CAS與鎖定