java.util.concurrent.atomic
AtomicInteger
是一个常用作与计数器的原子Integer
类,该类实现了并发下高效率的加减操作.
atomic
意思为原子性的,顾名思义,该包下面的类都是与原子性操作有关:不可中断的操作.
java.util.concurrent.atomic
包下面的实现原理与AtomicInteger
基本相似.
源码分析
java.util.concurrent.atomic.AtomicInteger
的源码比较容易理解:
- 成员属性有
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;
-
当值进行更新时候,采用比较交换模式:即不断循环仅当
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); }
-
比较交换的参考实现 简单参考实现,帮助解读,并非真实实现
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; } }