【Java并发编程】深入分析AtomicInteger(二)
线程安全,并发,编程,AtomicInteger,Unsafe2016-07-20
如果一个类可以安全地被多个线程使用,它就是线程安全的。你无法对此论述提出任何争议,但也无法从中得到更多有意义的帮助。那么我们如何辨别线程安全与非线程安全的类?我们甚至又该如何理解“安全”呢? 任何一个合理的“线程安全性”定义,其关键在于“正确性”的概念。在<<JAVA CONCURRENCY IN PRACTICE>>书中作者是这样定义的:一个类是是线程安全的,是指在被多个线程访问时,类可以持续进行正确的行为。
提示:书中作者还写到,如下:
当多个线程访问一个类时,如果不用考虑这些线程在运行时环境下的调度和交替执行,并且不需要额外的同步及在调用方代码不必作其他的协调,这个类的行为仍然是正确的,那么称这个类是线程安全的。
package com.lll.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class UnsafeCount {
//public static AtomicInteger count = new AtomicInteger(0);
public static int count = 0;
public static void inc() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//count.incrementAndGet();
count++;
}
public static void main(String[] args) throws InterruptedException {
ExecutorService service=Executors.newFixedThreadPool(Integer.MAX_VALUE);
for (int i = 0; i < 100; i++) {
service.execute(new Runnable() {
@Override
public void run() {
UnsafeCount.inc();
}
});
}
service.shutdown();
//避免出现main主线程先跑完而子线程还没结束,在这里给予一个关闭时间
service.awaitTermination(3000,TimeUnit.SECONDS);
System.out.println("运行结果:UnsafeCount.count=" + UnsafeCount.count);
}
}
运行结果:UnsafeCount.count=92
运行结果:UnsafeCount.count=98
....
根据结果可以看出在多线程环境下,没有获得期望的正确结果100.
package com.lll.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class UnsafeCount {
public static AtomicInteger count = new AtomicInteger(0);
//public static int count = 0;
public static void inc() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.incrementAndGet();
//count++;
}
public static void main(String[] args) throws InterruptedException {
ExecutorService service=Executors.newFixedThreadPool(Integer.MAX_VALUE);
for (int i = 0; i < 100; i++) {
service.execute(new Runnable() {
@Override
public void run() {
UnsafeCount.inc();
}
});
}
service.shutdown();
//避免出现main主线程先跑完而子线程还没结束,在这里给予一个关闭时间
service.awaitTermination(3000,TimeUnit.SECONDS);
System.out.println("运行结果:UnsafeCount.count=" + UnsafeCount.count);
}
}
运行结果:UnsafeCount.count=100
// 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); }
}
从上面的UML类图和代码可以看出AtomicInteger和Unsafe存在关联关系。它在类中获取了Unsafe的实例,然后通过Unsafe实例的objectFieldOffset方法获得value在内存中的位置。为什么它要获取value在内存中的位置?我们从incrementAndGet方法依次往下分析
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
第一步:通过get()方法获得value的值+1,然后传给了compareAndSet方法。compareAndSet代码如下:
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
+------------------------------------------------------------------+
“ Atomically sets the value to the given updated value if the current value {@code ==} the expected value.@return true if successful. False return indicates that the actual value was not equal to the expected value.”
+------------------------------------------------------------------+
第二步:compareAndSet()方法拿到原值和要更新的值。通过代码上的注释,我们可以知道如果valueOffset位置包含的值与expect值相同,则更新valueOffset位置的值为update,并返回true,否则不更新,返回false。