java.util.concurrent.atomic

AtomicInteger是一个常用作与计数器的原子Integer类,该类实现了并发下高效率的加减操作.

atomic意思为原子性的,顾名思义,该包下面的类都是与原子性操作有关:不可中断的操作.
java.util.concurrent.atomic包下面的实现原理与AtomicInteger基本相似.

源码分析

java.util.concurrent.atomic.AtomicInteger的源码比较容易理解:

  1. 成员属性有volatile修饰的值value,可以保证多线程下面的可见性.valueOffset存储value字段的内存位置,通过反射获取.unsafe则是底层硬件的实现.
     // setup to use Unsafe.compareAndSwapInt for updates
     private static final Unsafe unsafe = Unsafe.getUnsafe();
     private static final long valueOffset;
    	
     static {
       try {
         valueOffset = unsafe.objectFieldOffset
             (AtomicInteger.class.getDeclaredField("value"));
       } catch (Exception ex) { throw new Error(ex); }
     }
    	
     private volatile int value;
    
  2. 当值进行更新时候,采用比较交换模式:即不断循环仅当value为当前线程获取到的value相等时才进行更新操作(若不相等,则表明已被其他线程更新了)

     /**
      * 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 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);
     }
    
  3. 比较交换的参考实现 简单参考实现,帮助解读,并非真实实现

     class SimulatedCAS {
         private int value;
    	
         public synchronized int getValue() {
             return value;
         }
    	
         public synchronized int compareAndSwap(int expectedValue, int newValue) {
             int oldValue = value;
             if (value == expectedValue)
                 value = newValue;
             return oldValue;
         }
     }
    

来源

  1. 聊聊并发(五)原子操作的实现原理
  2. Java之美[从菜鸟到高手演练]之atomic包的原理及分析