`

[转]CAS的含义及Java中AtomicXXX类的分析

    博客分类:
  • java
阅读更多
维基百科:
In computer science, the compare-and-swap CPU instruction ("CAS") (or the Compare & Exchange - CMPXCHG instruction in the x86 and Itanium architectures) is a special instruction that atomically (regarding intel x86, lock prefix should be there to make it really atomic) compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. This guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple Boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it). Compare-and-Swap (and Compare-and-Swap-Double) has been an integral part of the IBM 370(and all successor) architectures since 1970. The operating systems which run on these architectures make extensive use of Compare-and-Swap (and Compare-and-Swap-Double) to facilitate process (i.e., system and user tasks) and processor (i.e., central processors) parallelism while eliminating, to the greatest degree possible, the "disabled spin locks" which were employed in earlier IBM operating systems. In these operating systems, new units of work may be instantiated "globally", into the Global Service Priority List, or "locally", into the Local Service Priority List, by the execution of a single Compare-and-Swap instruction. This dramatically improved the responsiveness of these operating systems.
===================================================
总结:CAS是硬件CPU提供的元语,它的原理:我认为位置 V 应该包含值 A;如果包含该值,则将 B 放到这个位置;否则,不要更改该位置,只告诉我这个位置现在的值即可。
Java并发库中的AtomicXXX类均是基于这个元语的实现,以AtomicInteger为例:

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

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


其中,unsafe.compareAndSwapInt()是一个native方法,正是调用CAS元语完成该操作。
===================================================
顺便说下volatile。
根据Java Language Specification中的说明, jvm系统中存在一个主内存(Main Memory或Java Heap Memory),Java中所有变量都储存在主存中,对于所有线程都是共享的。
每条线程都有自己的工作内存(Working Memory),工作内存中保存的是主存中某些变量的拷贝,线程对所有变量的操作都是在工作内存中进行,线程之间无法相互直接访问,变量传递均需要通过主存完成。
所以,同一变量的值在工作内存和主存中可能不一致。volatile其实是告诉处理器, 不要将我放入工作内存, 请直接在主存操作我。
===================================================
回到AtomicInteger,注意到value的声明:

private volatile int value;


通过前面对volatile的介绍可以知道,直接对volatile的赋值和读取操作是无须加锁的,见源码:

public final int get() {
        return value;
}

public final void set(int newValue) {
        value = newValue;
}


注意:volatile的这种作用对double和long无效,因为JVM中将对double或long的赋值或读取操作拆成2个32位数的操作。
===================================================
那么,为什么自增操作要通过CAS来完成呢?仔细观察incrementAndGet()方法,发现自增操作其实拆成了两步完成的:

int current = get(); 
int next = current + 1;


由于valatile只能保证读取或写入的是最新值,那么可能出现以下情况:
1 A线程执行get()操作,获取current值(假设为1)
2 B线程执行get()操作,获取current值(为1)
3 B线程执行next = current + 1操作,next = 2
4 A线程执行next = current + 1操作,next = 2
这样的结果明显不是我们想要的,所以,自增操作必须采用CAS来完成。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics