Java中,i++和++i都不是原子操作,多
线程环境下需要使用synchronized
关键字。JDK1.5的java.util.concurrent.atomic包提供了原子操作类,通过Unsafe类调native方法来实现。
这里以AtomicInteger为例:
内部存储
维护了一个整型值,其初始值为0。考虑到多线程操作,使用volatile来保证其可见性:
class="java">
private volatile int value;
单独赋值操作
通过
构造函数设置:
public AtomicInteger(int initialValue) {
value = initialValue;
}
Setter:
public final void set(int newValue) {
value = newValue;
}
延迟赋值:
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
获取和赋值复合操作:
Getter:
public final int get() {
return value;
}
获取原值并设置新值:
public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current, newValue))
return current;
}
}
获取原值并自增:
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
获取原值并自减:
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
获取原值并加上指定值:
delta可以为负值,实现getAndSubtract功能
public final int getAndAdd(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
自增并获取新值:
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
自减并获取新值:
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
加上指定值并获取新值:
同上,delta可以为负值,实现subtractAndGet功能
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
可以看出,上面的方法比较类似:
循环地调用compareAndSet方法,一旦成功即返回。
看下compreAndSet方法:
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
同时,还提供了weakCompareAndSet方法,调用的unsafe方法和上面相同:
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
性能测试
1. 和synchronized比较,单线程执行100w次自增操作:
public class AtomicIntegerSynchTest {
private int value;
public AtomicIntegerSynchTest(int value) {
this.value = value;
}
public synchronized int increase() {
return value++;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
AtomicIntegerSynchTest test = new AtomicIntegerSynchTest(0);
for (int i = 0; i < 10000000; i++) {
test.increase();
}
long end = System.currentTimeMillis();
System.out.println("Elapsed: " + (end - start) + "ms");
long start2 = System.currentTimeMillis();
AtomicInteger atomicInt = new AtomicInteger(0);
for (int i = 0; i < 10000000; i++) {
atomicInt.incrementAndGet();
}
long end2 = System.currentTimeMillis();
System.out.println("Elapsed: " + (end2 - start2) + "ms");
}
}
输出:
Elapsed: 383ms
Elapsed: 208ms (单线程环境下,AtomicInteger比
同步的性能稍好一点)
2. 多线程多次操作:
这里使用100个线程,每个线程执行1w次自增操作,为了统计100个线程并发执行所耗费的时间,使用CountDownLatch来协调。
public class AtomicIntegerMultiThreadTest {
private /*volatile*/ int value;
public AtomicIntegerMultiThreadTest(int value) {
this.value = value;
}
public synchronized int increase() {
return value++;
}
public int unSyncIncrease() {
return value++;
}
public int get() {
return value;
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
final CountDownLatch latch = new CountDownLatch(100);
final AtomicIntegerMultiThreadTest test = new AtomicIntegerMultiThreadTest(0);
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
test.increase();
//test.unSyncIncrease();
}
latch.countDown();
}
}).start();
}
latch.await();
long end = System.currentTimeMillis();
System.out.println("Elapsed: " + (end - start) + "ms, value=" + test.get());
long start2 = System.currentTimeMillis();
final CountDownLatch latch2 = new CountDownLatch(100);
final AtomicInteger atomicInt = new AtomicInteger(0);
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
atomicInt.incrementAndGet();
}
latch2.countDown();
}
}).start();
}
latch2.await();
long end2 = System.currentTimeMillis();
System.out.println("Elapsed: " + (end2 - start2) + "ms, value=" + atomicInt.get());
}
}
输出:
Elapsed: 1921ms, value=10000000
Elapsed: 353ms, value=10000000 (AtomicInteger的性能是synchronized的5倍多)
当给value加上volatile修饰符时:
Elapsed: 2268ms, value=10000000 (volatile禁止代码重排序,一定程度上降低了性能)
Elapsed: 337ms, value=10000000
当调用未同步的自增方法unSyncIncrease时:
Elapsed: 216ms, value=5852266 (非原子操作不加同步,导致结果
错误)
Elapsed: 349ms, value=10000000