class MyAtomicInteger{
private int value;
private final static long offset;
private final static Unsafe unsafe;
public MyAtomicInteger (int value) {
this.value = value;
}
static {
unsafe = UnsafeAccessor.getUnsafe();
try {
offset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
// compareAndSet
public int getAndCAS(int value) {
while (true) {
int prev = getValue();
if (unsafe.compareAndSwapInt(this, offset, prev, value)) {
return prev;
}
}
}
public int getValue() {
return this.value;
}
}
class UnsafeAccessor {
private static final Unsafe unsafe;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public static Unsafe getUnsafe() {
return unsafe;
}
}
Java 结合Unsafe 实现CAS AtomicInteger
最新推荐文章于 2023-02-09 13:24:49 发布