首页  

unsafe要点     所属分类 java 浏览量 1143
sun.misc.Unsafe


实例化一个类,不调用构造函数,不会初始化
修改私有字段 
抛出checked异常,方法签名上不需要声明
使用堆外内存  分配释放操作堆外内存
CAS操作 , AtomicInteger  使用 unsafe compareAndSwapInt 方法
阻塞/唤醒线程   park/unpark



Unsafe park() 阻塞线程
Unsafe unpark() 唤醒线程


使用 unsafe 分配释放堆外内存
long address = unsafe.allocateMemory(1024);
unsafe.freeMemory(address+2048);
越界释放会发生错误

java(63084,0x70000021a000) malloc: *** error for object 0x7fdcab002400: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
        


例子代码 import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeTest { private static class Pet { private int age = 9; public int getAge(){ return age; } } public static void main(String[] args) throws Exception { Unsafe unsafe = null; try{ unsafe = Unsafe.getUnsafe(); }catch(Throwable e){ System.out.println("getUnsafe error,"+e); } // 反射获取 Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); unsafe = (Unsafe) f.get(null); System.out.println("unsafe="+unsafe); Pet pet = new Pet(); System.out.println("age="+pet.getAge()); Pet pet2 = (Pet) unsafe.allocateInstance(Pet.class); // 0 , 只给对象分配内存 , 不会初始化 System.out.println("age2="+pet2.getAge()); // 直接设置私有变量值 Field ageField = Pet.class.getDeclaredField("age"); unsafe.putInt(pet2, unsafe.objectFieldOffset(ageField), 3); System.out.println("age3="+pet2.getAge()); try{ // Unsafe抛出checked异常不需要方法签名上声明 unsafeThrowCheckedException(unsafe); }catch(Exception e){ System.out.println(e); } long address = unsafe.allocateMemory(1024); unsafe.putInt(address, 7); unsafe.putInt(address+4, 8); System.out.println(unsafe.getInt(address)); System.out.println(unsafe.getInt(address+1)); System.out.println(unsafe.getInt(address+2)); System.out.println(unsafe.getInt(address+3)); System.out.println(unsafe.getInt(address+4)); System.out.println(unsafe.getInt(address+5)); //System.out.println(unsafe.getInt(address+2048)); unsafe.freeMemory(address); // java(63084,0x70000021a000) malloc: *** error for object 0x7fdcab002400: pointer being freed was not allocated // *** set a breakpoint in malloc_error_break to debug // unsafe.freeMemory(address+2048); } private static void unsafeThrowCheckedException(Unsafe unsafe){ unsafe.throwException(new Exception("unsafeThrowCheckedException test")); } }

上一篇     下一篇
java中的非阻塞IO和异步IO

NIO JMX BufferPool内存监控

AtomicInteger源码分析要点

DirectByteBuffer申请与释放

一行代码摧毁jvm

unix/linux基本理念和准则