Java Unsafe简单说明使用

本文探讨了如何在Java中使用sun.misc.Unsafe类进行内存操作,特别是Unsafe的compareAndSwapInt方法,以及其在AbstractQueuedSynchronizer中的应用实例。通过实例演示了如何利用Unsafe的objectFieldOffset方法获取字段偏移,实现原子状态修改。

Unsafe获取

 Unsafe unsafe = Unsafe.getUnsafe();

由于Unsafe为调用敏感,所以可能需要自行import,import sun.misc.Unsafe;

使用

compareAndSwapInt
public final native boolean compareAndSwapInt(Object object, long offset, int expect, int update);

该方法为native方法,CAS核心代码,比较并交换,该方法主要逻辑就是比较传入的expectobject偏移offset处对应的值是否相同,如果相同,则把update赋给偏移位置,并返回true,否则返回false

  • object: 操作对象;
  • offset: 偏移量,offset和object两个参数结合,可以确定object中某字段的内存地址;
    • unsafe.objectFieldOffset(Field field)获取非静态字段的offset;
    • unsafe.staticFieldOffset(Field field) 获取静态字段的offset;
  • expect : 期望值,用于和当前内存值进行比较,如果相等则用update替换并返回true,不等返回false;
  • update : 更新值,当前内存值与expect相同,则把update赋予内存值;

用例

java.util.concurrent.locks.AbstractQueuedSynchronizer部分源码

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long stateOffset;
    private static final long headOffset;
    private static final long tailOffset;
    private static final long waitStatusOffset;
    private static final long nextOffset;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
            headOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
            tailOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
            waitStatusOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("waitStatus"));
            nextOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("next"));

        } catch (Exception ex) { throw new Error(ex); }
    }
    /**
     * Atomically sets synchronization state to the given updated
     * value if the current state value equals the expected value.
     * This operation has memory semantics of a {@code volatile} read
     * and write.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that the actual
     *         value was not equal to the expected value.
     */
    protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰汁菠萝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值