Unsafe对象的创建

Unsafe对象提供了非常底层的,操作内存、线程的方法,Unsafe对象不能直接调用,只能通过反射获得。

public Class UnsafeAccessor{
    static Unsafe unsafe;
    
    static{
        try{
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        }catch(NoSuchFieldException | IllegalAccessException e){
            throw new Error(e);
        }
    }
    
    static Unsafe getUnsafe(){
        return unsafe;
    }
}
posted @ 2022-03-14 11:13  fjhnb  阅读(145)  评论(0)    收藏  举报