AtomicInteger 使用

Java中,i++和++i都不是原子操作,多线程环境下需要使用synchronized关键字。JDK1.5的java.util.concurrent.atomic包提供了原子操作类,通过Unsafe类调native方法来实现。

这里以AtomicInteger为例:

[b]内部存储[/b]

维护了一个整型值,其初始值为0。考虑到多线程操作,使用volatile来保证其可见性:

private volatile int value;


[b]单独赋值操作[/b]

通过构造函数设置:

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);
}


[b]获取和赋值复合操作:[/b]

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);
}



[b]性能测试[/b]

1. 和synchronized比较,单线程执行1000w次自增操作:


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("Synch 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("Atomic elapsed: " + (end2 - start2) + "ms");
}
}

输出:

Synch elapsed: 383ms
Atomic elapsed: 208ms (单线程环境下,AtomicInteger比同步的性能稍好一点)


2. 多线程多次操作:

这里使用100个线程,每个线程执行10w次自增操作,为了统计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("Synch 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("Atomic elapsed: " + (end2 - start2) + "ms, value=" + atomicInt.get());
}
}

输出:

Synch elapsed: 1921ms, value=10000000
Atomic elapsed: 353ms, value=10000000 (AtomicInteger的性能是synchronized的5倍多)

当给value加上volatile修饰符时:

Synch elapsed: 2268ms, value=10000000 (volatile禁止代码重排序,一定程度上降低了性能)
Atomic elapsed: 337ms, value=10000000

当调用未同步的自增方法unSyncIncrease时:

Synch elapsed: 216ms, value=5852266 (非原子操作不加同步,导致结果错误)
Atomic elapsed: 349ms, value=10000000
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值