Java并发编程(十一)Java中的原子操作类

一、原子操作类简介

JDK1.5开始提供了java.util.concurrent.atomic包,其中有一系列用法简单、性能高效、可以线程安全更新变量的原子操作类,目前(JDK1.7)大概有这么些:

二、原子操作类实现原理

以AtomicInteger为例看下源码,其中的两个方法getAndSet,getAndIncrement,都是无限循环调用compareAndSet,直到成功,CAS方法调用的是unsafe的方法,目前unsafe限制越来越严,也不建议程序员使用了,这里不做分析。源码如下:

public class AtomicInteger extends Number implements java.io.Serializable {
    

    /**
     * Atomically sets to the given value and returns the old value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final int getAndSet(int newValue) {
        for (;;) {
            int current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }


    /**
     * Atomically increments by one the current value.
     *
     * @return the previous value
     */
    public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;
        }
    }


    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }



}

猜你喜欢

转载自blog.csdn.net/ss1300460973/article/details/84785687
今日推荐