CAS(Compare and Swap),即比较并替换。jdk里的大量源码通过CAS来提供线程安全操作,比如AtomicInteger类。下面我们来分析一下AtomicInteger是如何在多线程的环境下保证线程安全的。在AtomicInteger里定义了用于存值的value变量,与用于操作value的Unsafe以及value变量的偏移量。源码如下:
public class AtomicInteger extends Number implements java.io.Serializable {
//unsafe来保证改变value的值是线程安全的
private static final Unsafe unsafe = Unsafe.getUnsafe();
//value值的偏移量
private static final long valueOffset;
//类初使化的时候通过unsafe能够得到变量的偏移量
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//这里声明为volatile,保证了线程间的可见性。
private volatile int value;
}
我们来分析一下AtomicInteger 做累加操作的源码:
//jdk的源码完全依赖于unsafe的操作。在这里需要传入的是当前对象, value的偏移量,和修改后的值
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
可以看出完全依赖于unsafe来完成线程安全,那unsafe类里是如何做的呢,截图如下:
Unsafe里如何修改值
在Eclipse默认是看不到sun的源码的,需要下载open jdk的源码进行关联,下载链接:https://github.com/keerath/openjdk-8-source。 采用CAS操作的前题假设是数据竟争不是很严重的情况,如果有大量的线程并发,while里的循环可能就要跑的时间很长了。那除了通过Unsafe类来实现CAS操作,我们还有其它的选择么?必竟Unsafe处于sun的包下面,一般的应用最好不依赖于这个包下面的类。
中间的*可以是Integer, Long, Reference(引用类型)。我们可以利用JDK给我们提供的API来实现CAS的操作。比如下面的小例子就实现了线程安全,代码如下:
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
public class AtomicTest {
//这里的变量需要设置成volatile
private volatile int lock = 0;
public static final AtomicIntegerFieldUpdater<AtomicTest> lockUpdate = AtomicIntegerFieldUpdater.newUpdater(AtomicTest.class, "lock");
public int add(int i) {
return lockUpdate.addAndGet(this, i);
}
public int get(){
return lockUpdate.get(this);
}
public static void main(String[] args) throws InterruptedException {
AtomicTest test = new AtomicTest();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for(int j=0; j<100; j++){
test.add(1);
}
}
});
t.start();
}
//这里sleep 1秒,等待上面线程跑完,实际代码不能这么写,可以用CountDownLatch
Thread.currentThread().sleep(1000);
//这里会输出1000
System.out.println(test.get());
}
}
AtomicIntegerFieldUpdater内部通过反身,得到需要操作的字段,同样是利用Unsafe类来实现CAS的操作,newUpdater相关源码如下:
//这个类是abstract, 不能构造对象
public abstract class AtomicIntegerFieldUpdater<T> {
@CallerSensitive
public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass,
String fieldName) {
//返回的是AtomicIntegerFieldUpdaterImpl对象
return new AtomicIntegerFieldUpdaterImpl<U>
(tclass, fieldName, Reflection.getCallerClass());
}
//这个类外部不能够访问,属于private
private static class AtomicIntegerFieldUpdaterImpl<T>
extends AtomicIntegerFieldUpdater<T> {
//通过Unsafe来实现CAS的操作
private static final Unsafe unsafe = Unsafe.getUnsafe();
//传入filed的偏移量
private final long offset;
private final Class<T> tclass;
private final Class<?> cclass;
//上面会调用的构造方法
AtomicIntegerFieldUpdaterImpl(final Class<T> tclass,
final String fieldName,
final Class<?> caller) {
final Field field;
final int modifiers;
try {
//通过反射得到对应的Feld
field = AccessController.doPrivileged(
new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
});
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
ClassLoader cl = tclass.getClassLoader();
ClassLoader ccl = caller.getClassLoader();
if ((ccl != null) && (ccl != cl) &&
((cl == null) || !isAncestor(cl, ccl))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Class<?> fieldt = field.getType();
if (fieldt != int.class)
throw new IllegalArgumentException("Must be integer type");
//需要声明为volatile
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) &&
caller != tclass) ? caller : null;
this.tclass = tclass;
//通过unsafe得到偏移量
offset = unsafe.objectFieldOffset(field);
}
}
}
CAS的算法通过判断内存的值是否与原值相等来进行修改操作,这就有可能会发生下面的问题。
ABA问题
如果场景是和过程状态无关的,只跟结果有关系,那么影响不大,但是有些情况之下,场景可能和过程有关的.当你对数据变化过程是敏感的时候,普通的CAS操作是无法辨别上图2个A的区别的。Java提供了AtomicStampedReference类用于处理ABA的问题,他通过类似版本号的机制来验证数据是否经过更改,用法如下:
//代码来源:https://blog.csdn.net/a67474506/article/details/48310515
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
public class ABA {
private static AtomicInteger atomicInt = new AtomicInteger(100);
private static AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<Integer>(100, 0);
public static void main(String[] args) throws InterruptedException {
Thread intT1 = new Thread(new Runnable() {
@Override
public void run() {
atomicInt.compareAndSet(100, 101);
atomicInt.compareAndSet(101, 100);
}
});
Thread intT2 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
boolean c3 = atomicInt.compareAndSet(100, 101);
System.out.println(c3); // true
}
});
intT1.start();
intT2.start();
intT1.join();
intT2.join();
Thread refT1 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
atomicStampedRef.compareAndSet(100, 101, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
atomicStampedRef.compareAndSet(101, 100, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
}
});
Thread refT2 = new Thread(new Runnable() {
@Override
public void run() {
int stamp = atomicStampedRef.getStamp();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
}
boolean c3 = atomicStampedRef.compareAndSet(100, 101, stamp, stamp + 1);
System.out.println(c3); // false
}
});
refT1.start();
refT2.start();
}
}