天使与魔鬼同在的Unsafe类详解

2 篇文章 0 订阅
public final class Unsafe {
  	private Unsafe() {
    }

    @CallerSensitive
    public static Unsafe getUnsafe() {
        Class var0 = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
            throw new SecurityException("Unsafe");
        } else {
            return theUnsafe;
        }
    }
}
特点:
1.该类不能被继承
2.该类不能被实例化(new)
3.该类不能被其他的clasLoader装载
有趣的获取实例方式
@CallerSensitive
public static Unsafe getUnsafe() {
	Class var0 = Reflection.getCallerClass();
	if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
		throw new SecurityException("Unsafe");
	} else {
		return theUnsafe;
	}
}


查看:VM.isSystemDomainLoader(var0.getClassLoader()) method
public static boolean isSystemDomainLoader(ClassLoader var0) {
        return var0 == null;
}

var0加载器为null
只有bootstarp classLoad为null 只能被bootstarp clasload加载
有没有办法获取到UnSafe对象呢?
private Unsafe unsafe;

    private int count = 0;

    private Object obj = new Object();

    public SafeDemo() {
        try {
            Class<Unsafe> unsafeClass = Unsafe.class;
            Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//可以通过反射获得
似曾相识的成员对象
	 /** @deprecated */
    @Deprecated
    public native void monitorEnter(Object var1);

    /** @deprecated */
    @Deprecated
    public native void monitorExit(Object var1);
    
    synchronized 中的monitorEnter/monitorExit
天使与魔鬼同在的方法
//直接操作内存
public native long allocateMemory(long var1);
//从内存中读取
public native long reallocateMemory(long var1, long var3);
使用UnSafe仿写synchronized锁
private Unsafe unsafe;

    private int count = 0;

    private Object obj = new Object();

    public void toSomeThing() {
        try {
            unsafe.monitorEnter(obj);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            unsafe.monitorExit(obj);
        }
    }

    public int getCount() {
        return count;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值