AtomicInteger,命名带有Atomic,很明显本身是原子性。这个类常是线程安全,多用于高并发对数据的修改。
关于多线程原子性,也顺带回顾下可见性
原子性
原子性具有不可分割的特性。原子操作,具有原子性。比如 i=0属于原子操作,再比如i++,实际是i = i + 1,是可分割的,属于非原子操作。非原子操作不是线程安全,在多线程中经常使用sychronized同步成原子操作。AtomicInteger、AtomicLong等是原子操作,在java.util.concurrent.atomic下
可见性
可见性,是指线程之间的可见性,则一个线程能可见另一个线程的操作结果。经常用volatile修饰的变量,代表具有可见性。volatile不能保证它具有原子性,是非线性安全。
下面代码对比体现AtomicInteger原子性
public classTestAtomicInteger {static int i = 0;static AtomicInteger a=new AtomicInteger(0);static class MyThread implementsRunnable {
synchronizedpublic voidrun() {for (int m = 0; m < 1000; m++) {
a.getAndIncrement();
i++;
}
}
};public static void main(String[] args) throwsException {
MyThread m= newMyThread();
Thread t1= newThread(m);
Thread t2= newThread(m);
t1.start();
t2.start();
System.out.println(i);
System.out.println(a.get());
}
}
加synchronized 输出结果
2000
2000
不加synchronized 输出结果
1986
2000
结果看出AtomicInteger是线程安全,是原子性的
下面分析下AtomicInteger源码:
//setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe =Unsafe.getUnsafe();private static final longvalueOffset;private volatile intvalue;static{try{
valueOffset=unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
}catch (Exception ex) { throw newError(ex); }
}
Unsafe类提供了硬件级别的原子操作,可以分配与释放内存,定位对象某字段的内存位置。源码注释是更新操作时提供“比较并替换”
valueOffset是用来记录内存地址偏移量
value被volatile修饰,更新操作时,当前线程可以拿到value最新的值
public final intincrementAndGet() {for(;;) {int current =get();int next = current + 1;if(compareAndSet(current, next))returnnext;
}
}public final boolean compareAndSet(int expect, intupdate) {return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
int current = get(); 这里可以获取value的最新值
unsafe.compareAndSwapInt(); 使用unsafe的native方法,实现高效的硬件级别CAS