CAS是項(xiàng)樂(lè)觀鎖技術(shù),當(dāng)多個(gè)線程嘗試使用CAS同時(shí)更新同一個(gè)變量時(shí),只有其中一個(gè)線程能更新變量的值,而其它線程都失敗,失敗的線程并不會(huì)被掛起,而是被告知這次競(jìng)爭(zhēng)中失敗,并可以再次嘗試。
樂(lè)觀鎖的一種實(shí)現(xiàn)方式——CAS
在JDK1.5 中新增java.util.concurrent(J.U.C)就是建立在CAS之上的。相對(duì)于對(duì)于synchronized這種阻塞算法,CAS是非阻塞算法的一種常見(jiàn)實(shí)現(xiàn)。所以J.U.C在性能上有了很大的提升。
借助CAS(AtomicReference)實(shí)現(xiàn)單例模式:
public final class SingleInstance {
private static final AtomicReference<SingleInstance> instanceRef = new AtomicReference<>();
private SingleInstance() {
}
public static SingleInstance getInstance() {
for (; ; ) {
SingleInstance instance = instanceRef.get();
if (instance != null) {
return instance;
}
instanceRef.compareAndSet(null, new SingleInstance());
}
}
}
與sychronized實(shí)現(xiàn)的單例相比
優(yōu)點(diǎn):
- 無(wú)鎖
缺點(diǎn):
- 對(duì)象可能會(huì)被創(chuàng)建多個(gè),設(shè)置失敗的會(huì)被舍棄
- 代碼相對(duì)稍微復(fù)雜
參考文章:
- https://www.cnblogs.com/snow-man/p/9970523.html 修正了文章中的錯(cuò)誤