Unsafe类的使用

一,简介

       Unsafe可以用于获取成员字段在类实例中的偏移量,直接操作变量在主内存中的值等操作。
       1,获取unsafe.objectFieldOffset(Field f)成员变量地址偏移量。

public class AtomicInteger extends Number implements java.io.Serializable {
    private static final long serialVersionUID = 6214790243416807050L;

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
      try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicInteger.class.getDeclaredField("value"));//获取该字段的偏移量
      } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value;//成员字段

    /**
     * Creates a new AtomicInteger with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicInteger(int initialValue) {
        value = initialValue;
    }
}
    2,根据字段偏移量获取实例中此字段的值。

 

  long offset = unsafe.objectFieldOffset(User.class.getDeclaredField("age"));
  Object obj = unsafe.getInt(this, offset);//获取int型值,getObject(),getLong()等
  System.out.println(obj);
   3,CAS算法支持
public class AtomicBoolean implements java.io.Serializable {

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);//如果主内存中的值是期望
        //的e则替换成u并返回true,否则返回false。
    }
}
   4,获取Unsafe实例
/**import sun.misc.Unsafe;导入此包
 * 反射获取该实例,还绕开了安全管理器的限制
 */
private static Unsafe getUnsafeInstance() throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
    Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
    theUnsafeInstance.setAccessible(true);
    return (Unsafe) theUnsafeInstance.get(Unsafe.class);//返回指定对象上此Field字段表示的值
 }
 
二,总结
    Unsafe提供了直接操作主内存(堆内存)的方法,但sun公司是通过安全管理器限制了直接获取Unsafe的,毕竟应用层直接操作主内存是不安全的,当然也是不允许的。更多关于Unsafe类的应用,请阅读JDK中原子类的实现。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值