CAS之基本类型与引用类型

CAS之基本类型与引用类型

1.1 long

static final Unsafe unsafe ;
static Long offset;
private volatile long  state= 1;

static {
    try {
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe = (Unsafe)field.get(null);    
        offset = unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
        throw new Error(e);
    }
}

public static void main(String[] args) {
    TestUnsafe testUnsafe = new TestUnsafe();
    boolean success = unsafe.compareAndSwapLong(testUnsafe,offset,1,3);
    System.out.println("sucess:"+success+" after cas:"+testUnsafe.state);
}

1.2 Long

static final Unsafe unsafe ;
static Long offset;
//等同于Long.valueOf(1L)==>new Long(1L),是引用类型
private volatile Long  state= 1L;

static {
​    try {
​        Field field = Unsafe.class.getDeclaredField("theUnsafe");
​        field.setAccessible(true);
​        unsafe = (Unsafe)field.get(null);    
​        offset = unsafe.objectFieldOffset(TestUnsafe2.class.getDeclaredField("state"));
​    } catch (Exception e) {
​        System.out.println(e.getLocalizedMessage());
​        throw new Error(e);
​    }
}
public static void main(String[] args) {
​    TestUnsafe2 testUnsafe = new TestUnsafe2();
​    boolean success = unsafe.compareAndSwapObject(testUnsafe,offset,1L,3L);
​    //此处若换成 boolean success = unsafe.compareAndSwapLong(testUnsafe,offset,1L,3L);将失败,因为state是引用类型,不能用直接实际的值来比较,而应该用引用的实际内存地址做对比
​    System.out.println("sucess:"+success+" after cas:"+testUnsafe.state);
}

​

评论

暂无评论