AtomicInteger  是用 CAS(Compre And Swap,乐观锁) 构造的一个 原子类。

1. CAS 

CAS(Compare and Swap)比较并替换,CAS是实现乐观锁的一个重要操作。CAS 是一个硬件指令,保证是原子操作,Java 中通过 UnSafe 来实现。详细可一下我的这篇博文:传送。

CAS 的基本步骤:执行函数 CAS(V,E,N),如果V值等于E值,则将V的值设为N。若V值和E值不同,则说明已经有其他线程做了更新,则当前线程什么都不做。

          (1)V表示要更新的变量

          (2)E表示预期值

          (3)N表示新值

2. 源码阅读

UnSafe 类,Java 中通过 UnSafe 来实现 CAS。

private static final Unsafe unsafe = Unsafe.getUnsafe();

value 值的偏移量。

private static final long valueOffset;

 静态语句块, 初始化 valueOffset。

在类的加载过程中,类的static成员变量会被初始化,另外,如果类中有static语句块,则会执行static语句块。static成员变量和static语句块的执行顺序同代码中的顺序一致。Java 中的类与对象

初始化阶段是执行类构造器 <clinit>() 方法的过程,<clinit>() 方法是编译器自动收集类中的所有类变量和 静态语句块 (static{}块)中的语句合并产生的,编译器的收集顺序是按照语句在源文件中的顺序所决定的,静态语句块只能访问定义在静态语句块之前的变量,定义在之后的变量可以赋值,但不可以被访问。

<clinit>() 方法是同步方法:虚拟机保证类的 <clinit>() 方法是在多线程的环境下被正确的加锁、同步。如果多个线程同时初始化一个类,那么只会有一个线程执行 <clinit>() 方法, 其他线程需要去阻塞等待,如果一个类的 <clinit>() 方法有耗时的操作,就可能会阻塞多个进程。JVM虚拟机的类加载。

static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

value 值,voliate 修饰,保持可见性。

private volatile int value;

构造函数,initialValue 为一个初始值:

public AtomicInteger(int initialValue) {
        value = initialValue;
    }
public AtomicInteger() {
    }

 获取 value 的值。

public final int get() {
        return value;
    }

设置 value 的值。

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

 懒加载,设置新值,不保证立即更新。

this 是 当前对象,在使用 valueOffset 偏移值就可以得到 value,然后懒加载的设置新值。

public final void lazySet(int newValue) {
        unsafe.putOrderedInt(this, valueOffset, newValue);
    }

以原子方式设置新值,并返回旧值,

public final int getAndSet(int newValue) {
        return unsafe.getAndSetInt(this, valueOffset, newValue);
}

以原子方式,如果 实例值 == expect (期望值),则设置实例值为 update(更新的值),

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

这个方法和上面的源码一样,emm,在网上搜了一下。

答案:。

由此可见,在JDK8乃至之前的版本,weakCompareAndSet方法并没有被真是意义上的实现,目前该方法所呈现出来的效果与 compareAndSet 方法是一样的。

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

 以原子方式当前值+1,返回+1前的值。

public final int getAndIncrement() {
        return unsafe.getAndAddInt(this, valueOffset, 1);
    }

以原子方式当前值-1,返回-1前的值。

public final int getAndDecrement() {
        return unsafe.getAndAddInt(this, valueOffset, -1);
    }

以原子方式当前值+delta,返回+delta前的值。

public final int getAndAdd(int delta) {
        return unsafe.getAndAddInt(this, valueOffset, delta);
    }

以原子方式当前值+1,返回+1后的值。

public final int incrementAndGet() {
        return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
    }

以原子方式当前值-1,返回-1后的值。

public final int decrementAndGet() {
        return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
    }

以原子方式当前值+delta,返回+delta后的值。

public final int addAndGet(int delta) {
        return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
    }

以原子方式当前值+delta,返回+delta后的值。

public final int getAndUpdate(IntUnaryOperator updateFunction) {
        int prev, next;
        do {
            prev = get();
            next = updateFunction.applyAsInt(prev);
        } while (!compareAndSet(prev, next));
        return prev;
    }

更新并且获得值。

首先我们看下  IntUnaryOperator,将函数,变为,参数传入。是一个接口,就是将一个对int类型的操作当一个参数传入进来。关键函数:applyAsInt(int operand),对一个参数operand进行一些操作,最后返回个int类型。

public final int updateAndGet(IntUnaryOperator updateFunction) {
        int prev, next;
        do {
            // 当前值
            prev = get();
            // 预期值
            next = updateFunction.applyAsInt(prev);
        } while (!compareAndSet(prev, next));
        return next;
    }

举个例子,实现 IntUnaryOperator ,类如下所示:

class My1 implements IntUnaryOperator {

    @Override
    public int applyAsInt(int operand) {
        return operand + 5;
    }
}

 调用 实现类 My1, atomicIntenger  +5 。

atomicInteger.updateAndGet(new My1());

IntBinaryOperator 源码 :

@FunctionalInterface
public interface IntBinaryOperator {
    int applyAsInt(int left, int right);
}

对照  IntBinaryOperator ,可得 期望着等于   IntBinaryOperator 实现类中的计算方法,left 为当前值,right 为 x;

public final int getAndAccumulate(int x,
                                      IntBinaryOperator accumulatorFunction) {
        int prev, next;
        do {
            // 当前值
            prev = get();
            // 期望值
            next = accumulatorFunction.applyAsInt(prev, x);
        } while (!compareAndSet(prev, next));
        return prev;
    }

举一个例子:实现类 My2如下所示, atomicInteger.accumulateAndGet(5, new My2()), 当前值 - 5 ;

class My2 implements IntBinaryOperator {
    @Override
    public int applyAsInt(int left, int right) {
        return left - right;
    }
}

getAndAccumulate 是 获得原值然后计算,accumulateAndGet 是计算后获得原值。

public final int accumulateAndGet(int x,
                                      IntBinaryOperator accumulatorFunction) {
        int prev, next;
        do {
            prev = get();
            next = accumulatorFunction.applyAsInt(prev, x);
        } while (!compareAndSet(prev, next));
        return next;
    }

toString, 获取不同类型的 value 值。

public String toString() {
        return Integer.toString(get());
    }

    public int intValue() {
        return get();
    }

    public long longValue() {
        return (long)get();
    }
    public float floatValue() {
        return (float)get();
    }
    public double doubleValue() {
        return (double)get();
    }

参考文献

  • Java并发编程的艺术 / 方腾飞,魏鹏,魏晓明著 .  ——北京:机械工业出版社,2015.7