Java語言中cas指令的無鎖編程實(shí)現(xiàn)實(shí)例
最開始接觸到相關(guān)的內(nèi)容應(yīng)該是從volatile關(guān)鍵字開始的吧,知道它可以保證變量的可見性,而且利用它可以實(shí)現(xiàn)讀與寫的原子操作。。。但是要實(shí)現(xiàn)一些復(fù)合的操作volatile就無能為力了。。。最典型的代表是遞增和遞減的操作。。。。
我們知道,在并發(fā)的環(huán)境下,要實(shí)現(xiàn)數(shù)據(jù)的一致性,最簡單的方式就是加鎖,保證同一時刻只有一個線程可以對數(shù)據(jù)進(jìn)行操作。。。。例如一個計數(shù)器,我們可以用如下的方式來實(shí)現(xiàn):
public class Counter {
private volatile int a = 0;
public synchronized int incrAndGet(int number) {
this.a += number;
return a;
}
public synchronized int get() {
return a;
}
}
我們對操作都用synchronized關(guān)鍵字進(jìn)行修飾,保證對屬性a的同步訪問。。。這樣子確實(shí)可以保證在并發(fā)環(huán)境下a的一致性,但是由于使用了鎖,鎖的開銷,線程的調(diào)度等等會使得程序的伸縮性受到了限制,于是就有了很多無鎖的實(shí)現(xiàn)方式。。。。
其實(shí)這些無鎖的方法都利用了處理器所提供的一些CAS(compare and switch)指令,這個CAS到底干了啥事情呢,可以用下面這個方法來說明CAS所代表的語義:
public synchronized int compareAndSwap(int expect, int newValue) {
int old = this.a;
if (old == expect) {
this.a = newValue;
}
return old;
}
好吧,通過代碼應(yīng)該對CAS語義的標(biāo)書很清楚了吧,好像現(xiàn)在大多數(shù)的處理器都實(shí)現(xiàn)了原子的CAS指令了吧。。
好啦,那么接下來來看看在java中CAS都用在了什么地方了吧,首先來看AtomicInteger類型吧,這個是并發(fā)庫里面提供的一個類型:
private volatile int value;
這個是內(nèi)部定義的一個屬性吧,用于保存值,由于是volatile類型的,所以可以保證線程之間的可見性以及讀寫的原子性。。。
那么接下來來看看幾個比較常用的方法:
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
這個方法的作用是在當(dāng)前值的基礎(chǔ)上加上delta,這里可以看到整個方法中并沒有加鎖,這代碼其實(shí)就算是java中實(shí)現(xiàn)無鎖計數(shù)器的方法,這里compareAndSet方法的定義如下:
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
由于調(diào)用了unsafe的方法,所以這個就無能為力了,其實(shí)應(yīng)該能猜到JVM調(diào)用了處理器本身的CAS指令來實(shí)現(xiàn)原子的操作。。。
基本上AtomicInteger類型的重要方法都是采用無鎖的方式實(shí)現(xiàn)的。。因此在并發(fā)環(huán)境下,用這種類型能有更好的性能。。。
上面算是搞定了在java中實(shí)現(xiàn)無鎖的計數(shù)器,接下來來看看如何實(shí)現(xiàn)無鎖棧,直接貼代碼了,代碼是從《JAVA并發(fā)編程實(shí)戰(zhàn)》中模仿下來的:
package concurrenttest;
import java.util.concurrent.atomic.AtomicReference;
public class ConcurrentStack<e> {
AtomicReference<node<e>> top = new AtomicReference<node<e>>();
public void push(E item) {
Node<e> newHead = new Node<e>(item);
Node<e> oldHead;
while (true) {
oldHead = top.get();
newHead.next = oldHead;
if (top.compareAndSet(oldHead, newHead)) {
return;
}
}
}
public E pop() {
while (true) {
Node<e> oldHead = top.get();
if (oldHead == null) {
return null;
}
Node<e> newHead = oldHead.next;
if (top.compareAndSet(oldHead, newHead)) {
return oldHead.item;
}
}
}
private static class Node<e> {
public final E item;
public Node<e> next;
public Node(E item) {
this.item = item;
}
}
}
好啦,上面的代碼就算是實(shí)現(xiàn)了一個無鎖的棧,簡單吧。。。在并發(fā)環(huán)境中,無鎖的數(shù)據(jù)結(jié)構(gòu)伸縮性能夠比用鎖好得多。。。
在提到無鎖編程的時候,就不得不提到無鎖隊(duì)列,其實(shí)在concurrent庫中已經(jīng)提供了無鎖隊(duì)列的實(shí)現(xiàn):ConcurrentLinkedQueue,我們來看看它的重要的方法實(shí)現(xiàn)吧:
public boolean offer(E e) {
checkNotNull(e);
final Node<e> newNode = new Node<e>(e);
for (Node<e> t = tail, p = t;;) {
Node<e> q = p.next;
if (q == null) {
// p is last node
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
這個方法用于在隊(duì)列的尾部添加元素,這里可以看到?jīng)]有加鎖,對于具體的無鎖算法,采用的是Michael-Scott提出的非阻塞鏈表鏈接算法。。。具體是怎么樣子的,可以到《JAVA并發(fā)編程實(shí)戰(zhàn)》中去看吧,有比較詳細(xì)的介紹。
另外對于其他方法,其實(shí)都是采用無鎖的方式實(shí)現(xiàn)的。
最后,在實(shí)際的編程中,在并發(fā)環(huán)境中最好還是采用這些無鎖的實(shí)現(xiàn),畢竟它的伸縮性更好。
總結(jié)
以上是本文關(guān)于Java語言中cas指令的無鎖編程實(shí)現(xiàn)實(shí)例的全部介紹,希望對大家有所幫助!
相關(guān)文章
解決復(fù)制springboot項(xiàng)目后,啟動日志無顏色的問題
這篇文章主要介紹了解決復(fù)制springboot項(xiàng)目后,啟動日志無顏色的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java 并發(fā)編程學(xué)習(xí)筆記之Synchronized簡介
雖然多線程編程極大地提高了效率,但是也會帶來一定的隱患。比如說兩個線程同時往一個數(shù)據(jù)庫表中插入不重復(fù)的數(shù)據(jù),就可能會導(dǎo)致數(shù)據(jù)庫中插入了相同的數(shù)據(jù)。今天我們就來一起討論下線程安全問題,以及Java中提供了什么機(jī)制來解決線程安全問題。2016-05-05
SpringIOC refresh()初始化代碼實(shí)例
這篇文章主要介紹了SpringIOC refresh()初始化代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03
java定義通用返回結(jié)果類ResultVO使用示例詳解
這篇文章主要為大家介紹了java定義通用返回結(jié)果類ResultVO使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09

