原子类的线程安全性原理

以AtomicInteger来说明

1.value实例变量是用来存储整数的时间变量,这里被声明为volatile,确保了并发情况下的可见性

2.valueOffset实例变量是用来记录value本身在内存的偏移地址,在更新操作在内存中找到value的位置,方便比较。

3.以getAndSet为例。使用了Unsafe 的getAndInt方法,该方法先取AtomicInteger存储的value值,然后调用compareAndSwapInt方法(native方法),一直到compareAndSwapInt返回true时循环操作。

4.compareAndSwapInt方法根据根据offset获取o的value值,若value和v相同,设置value值为newValue,返回true;否则返回false。

/**
     * 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) {
        return unsafe.getAndSetInt(this, valueOffset, newValue);
    }
public final int getAndSetInt(Object o, long offset, int newValue) {
        int v;
        do {
            v = this.getIntVolatile(o, offset);
        } while(!this.compareAndSwapInt(o, offset, v, newValue));

        return v;
    }

 

优缺点

1.避免了多线程下对共享变量必须加锁进行访问,提高效率。

2.存在ABA问题。

posted @ 2017-02-22 15:17  lion85  阅读(286)  评论(0编辑  收藏  举报