原子變數與非阻塞的同步機制
一、鎖的劣勢
1.在多執行緒下:鎖的掛起和復原等過程存在著很大的開銷(及時現代的jvm會判斷何時使用掛起,何時自旋等待)
2.volatile:輕量級級別的同步機制,但是不能用於構建原子複合操作
因此:需要有一種方式,在管理執行緒之間的競爭時有一種粒度更細的方式,類似與volatile的機制,同時也要支援原子更新操作
二、CAS
#獨佔鎖是一種悲觀的技術--它假設最壞的情況,所以每個線程是獨佔的
而CAS比較並交換:compareAndSwap/Set(A,B):我們認為內存處值是A,如果是A,將其修改為B,否則不進行操作;傳回記憶體處的原始值或是否修改成功
如:模擬CAS運算
//模拟的CASpublic class SimulatedCAS {private int value;public synchronized int get() {return value; }//CAS操作public synchronized int compareAndSwap(int expectedValue, int newValue) {int oldValue = value;if (oldValue == expectedValue) { value = newValue; }return oldValue; }public synchronized boolean compareAndSet(int expectedValue, int newValue) {return (expectedValue == compareAndSwap(expectedValue, newValue)); } }//典型使用场景public class CasCounter {private SimulatedCAS value;public int getValue() {return value.get(); }public int increment() {int v;do { v = value.get(); } while { (v != value.compareAndSwap(v, v + 1)); }return v + 1; } }
#
JAVA提供了CAS的操作
原子狀態類別:AtomicXXX的CAS方法
# 原子狀態類別:AtomicXXX的CAS方法
# JAVA7/8:對Map的操作:
JAVA7/8:對Map的操作:putIfAbs、computerIf.Pcomputerf. ....三、原子變數類別 AtomicRefence原子更新對象,可以是自訂的對象;如:public class CasNumberRange {private static class IntPair {// INVARIANT: lower values = new AtomicReference<intpair>(new IntPair(0, 0)); //封装对象public int getLower() {return values.get().lower; }public int getUpper() {return values.get().upper; }public void setLower(int i) {while (true) { IntPair oldv = values.get();if (i > oldv.upper) {throw new IllegalArgumentException("Can't set lower to " + i + " > upper"); } IntPair newv = new IntPair(i, oldv.upper); //属性为不可变域,则每次更新新建对象if (values.compareAndSet(oldv, newv)) { //原子更新,如果在过程中有线程修改了,则其他线程不会更新成功,因为oldv与内存处值就不同了return; } } }//同上public void setUpper(int i) {while (true) { IntPair oldv = values.get();if (i <p></p> <p></p> 效能問題:使用原子變數在中低並發(競爭)下,比使用鎖定速度快,一般情況下是比鎖定速度快的<h3></h3> <p></p>#四、非阻塞演算法<p></p> 許多常見的資料結構中都可以使用非阻塞演算法<p></p> 非阻塞演算法:在多執行緒中,工作是否成功有不確定性,需要循環執行,並且透過CAS進行原子運算<p></p> 1、上面的CasNumberRange<div class="cnblogs_code"></div> 2、堆疊的非阻塞演算法:只儲存頭部指針,只有一個狀態<p></p> <pre class="brush:php;toolbar:false">//栈实现的非阻塞算法:单向链表public class ConcurrentStack <e> { AtomicReference<node>> top = new AtomicReference<node>>();public void push(E item) { Node<e> newHead = new Node<e>(item); Node<e> oldHead;do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead));//CAS操作:原子更新操作,循环判断,非阻塞 }public E pop() { Node<e> oldHead; Node<e> newHead;do { oldHead = top.get();if (oldHead == null) {return null; } newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead));//CAS操作:原子更新操作,循环判断,非阻塞return oldHead.item; }private static class Node <e> {public final E item;public Node<e> next;public Node(E item) {this.item = item; } } }</e></e></e></e></e></e></e></node></node></e>
3、鍊錶的非阻塞演算法:頭部和尾部的快速訪問,保存兩個狀態,更加複雜
public class LinkedQueue <e> {private static class Node <e> {final E item;final AtomicReference<linkedqueue.node>> next;public Node(E item, LinkedQueue.Node<e> next) {this.item = item;this.next = new AtomicReference<linkedqueue.node>>(next); } }private final LinkedQueue.Node<e> dummy = new LinkedQueue.Node<e>(null, null);private final AtomicReference<linkedqueue.node>> head = new AtomicReference<linkedqueue.node>>(dummy);private final AtomicReference<linkedqueue.node>> tail = new AtomicReference<linkedqueue.node>>(dummy); //保存尾节点public boolean put(E item) { LinkedQueue.Node<e> newNode = new LinkedQueue.Node<e>(item, null);while (true) { LinkedQueue.Node<e> curTail = tail.get(); LinkedQueue.Node<e> tailNext = curTail.next.get();if (curTail == tail.get()) {if (tailNext != null) {// 处于中间状态,更新尾节点为当前尾节点的next tail.compareAndSet(curTail, tailNext); } else {// 将当前尾节点的next 设置为新节点:链表if (curTail.next.compareAndSet(null, newNode)) {/** * 此处即为中间状态,虽然在这里进行了两次原子操作,整体不是原子的,但是通过算法保证了安全: * 原因是处于中间状态时,如果有其他线程进来操作,则上面那个if将执行; * 上面if的操作是来帮助当前线程完成更新尾节点操作,而当前线程的更新就会失败返回,最终则是更新成功 */// 链接成功,尾节点已经改变,则将当前尾节点,设置为新节点 tail.compareAndSet(curTail, newNode);return true; } } } } } }</e></e></e></e></linkedqueue.node></linkedqueue.node></linkedqueue.node></linkedqueue.node></e></e></linkedqueue.node></e></linkedqueue.node></e></e>3.原子域更新器
上面的邏輯,實作了鍊錶的非阻塞演算法,使用Node來保存頭結點和尾節點 在實際的ConcurrentLinkedQueue# 在實際的ConcurrentLinkedQueue中使用的是基於反射的
AtomicReferenceFiledUpdater來包裝Node
五、ABA問題
## CAS運算中容易出現的問題: CAS運算中容易出現的問題: 是否為A,是的話就繼續更新操作換成B; 但是如果一個線程將值A改為C,然後又改回A,此時,原線程將判斷A=A成功執行更新操作; 如果把A改為C,然後又改回A的操作,也需要視為變化,則需要對演算法進行優化 解決:新增版本號,每次更新操作要更新版本號,即使值是一樣的###### ####### ###以上是java並發程式設計(8)原子變數和非阻塞的同步機制的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

禪工作室 13.0.1
強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器