java-并发-CAS&非阻塞算法

一. CAS

对于例子:

if(a==b) {  
    a++;  
} 

如果a++之前,a的值改变了怎么办
CAS可以实现无锁,这样如果a的值被改变了a++就不会被执行

int expect = a;  
compareAndSet(a,expect,a+1)

如果想执行a++操作需要while循环

while(true) {  
    int expect = a;  
    if (compareAndSet(a, expect, a + 1)) {    
        return;  
    }
}  

二. java中的CAS

用的Unsafe类的CAS操作完成的

public final boolean compareAndSet(int expect, int update) {  
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);  
}  

a++操作

public final int getAndIncrement() {  
    for (;;) {  
        int current = get();  
        int next = current + 1;  
        if (compareAndSet(current, next))  
            return current;  
    }  
}  

++a操作,只是返回结果不同

public final int incrementAndGet() {  
    for (;;) {  
        int current = get();  
        int next = current + 1;  
        if (compareAndSet(current, next))  
            return next;  
    }  
}  

ConcurrentLinkedQueue类都是采用CAS实现

三. 缺点

ABA问题
花费CPU资源
增加程序测试的复杂度

四. 非阻塞算法

非阻塞算法:http://www.ibm.com/developerworks/cn/java/j-jtp04186/

posted @ 2016-09-02 21:29  zhangshihai1232  阅读(146)  评论(0)    收藏  举报