unsafe类使用demo

public class UnsafeUseDemo {
    long sizeCtl;
    long transferIndex;
    public static void main(String[] args) {
        UnsafeUseDemo unsafeUseDemo = new UnsafeUseDemo();
        System.out.println(unsafeUseDemo.transferIndex);
        unsafeUseDemo.cas();
        System.out.println(unsafeUseDemo.transferIndex);
    }

    public boolean cas(){
        return U.compareAndSwapInt(this, TRANSFERINDEX, 0, 1);
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe U;
    private static final long SIZECTL;
    private static final long TRANSFERINDEX;

    static {
        try {
            // 获取unsafe类
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            U = (Unsafe) f.get(null);

            Class<?> k = UnsafeUseDemo.class;
            SIZECTL = U.objectFieldOffset
                    (k.getDeclaredField("sizeCtl"));
            TRANSFERINDEX = U.objectFieldOffset
                    (k.getDeclaredField("transferIndex"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

你可能感兴趣的:(并发编程,java后端,java,开发语言,后端)