CAS
CAS(Compare-and-Swap),即比較並替換,是一種樂觀鎖技術,在併發算法時常用到的技術
AtomicInteger 中cas的應用
value 需要用volatile修飾,保證可見性
public class AtomicInteger extends Number implements java.io.Serializable {
private volatile int value;
public final int get() {
return value;
}
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
}
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
調用JNI本地方法
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
比較內存值與當前值是否一致,如果一致,則將內存當前的值替換爲修改值,如果不一致放棄修改,則重新獲取內存值,循環重試操作
if (this == expect) {
this = update
return true;
} else {
return false;
}
CAS 算法在ConcurrentLinkedQueue中的應用
它必須先獲取尾節點,然後設置尾節點的下一個節點爲入隊節點,但這時可能有另外一個線程插隊了,那麼隊列的尾節點就會發生變化,這時當前線程要暫停入隊操作,然後重新獲取尾節點。讓我們再通過源碼來詳細分析下它是如何使用CAS算法來入隊的。
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
//入隊前,創建一個入隊節點
Node</e><e> n = new Node</e><e>(e);
retry:
//死循環,入隊不成功反覆入隊。
for (;;) {
//創建一個指向tail節點的引用
Node</e><e> t = tail;
//p用來表示隊列的尾節點,默認情況下等於tail節點。
Node</e><e> p = t;
for (int hops = 0; ; hops++) {
//獲得p節點的下一個節點。
Node</e><e> next = succ(p);
//next節點不爲空,說明p不是尾節點,需要更新p後在將它指向next節點
if (next != null) {
//循環了兩次及其以上,並且當前節點還是不等於尾節點
if (hops > HOPS && t != tail)
continue retry;
p = next;
}
//如果p是尾節點,則設置p節點的next節點爲入隊節點。
else if (p.casNext(null, n)) {
//如果tail節點有大於等於1個next節點,則將入隊節點設置成tair節點,更新失敗了也沒關係,因爲失敗了表示有其他線程成功更新了tair節點。
if (hops >= HOPS)
casTail(t, n); // 更新tail節點,允許失敗
return true;
}
// p有next節點,表示p的next節點是尾節點,則重新設置p節點
else {
p = succ(p);
}
}
}
}
retry:標記位置,內層循環continue後直接跳到外層開始執行了
複製鏈接,在瀏覽器打開
tomcat源碼解析
https://study.163.com/course/introduction/1209535854.htm
Springmvc源碼解析
https://study.163.com/course/introduction/1209536851.htm