首页  

DirectByteBuffer申请与释放     所属分类 java 浏览量 1454
DirectByteBuffer 堆外分配内存
ByteBuffer bf = ByteBuffer.allocateDirect(size);
堆外内存的分配和释放使用 unsafe 

long base = unsafe.allocateMemory(size)
allocateMemory 成功返回堆外内存地址

Bits.reserveMemory(size, cap);

// 释放直接内存
unsafe.freeMemory(address);
address = 0;
Bits.unreserveMemory(size, capacity);
        
 
private static volatile long maxMemory = VM.maxDirectMemory();
private static final AtomicLong reservedMemory = new AtomicLong();
private static final AtomicLong totalCapacity = new AtomicLong();
private static final AtomicLong count = new AtomicLong();
   
跟踪 DirectByteBuffer 使用情况

DirectByteBuffer类实例放在堆内,通过基类Buffer的capacity,long address两个变量指向堆外内存,
DirectByteBuffer类实例A没有被引用,在触发GC前,jvm把A放到PhantomReference队列里,
同时不断扫描PhantomReference队列,取出A,调用 Deallocator里的run方法回收堆外内存 
堆外内存的回收依赖GC

-XX:+DisableExplicitGC  禁用GC可能导致堆外内存无法回收
java.lang.OutOfMemoryError: Direct buffer memory 

cms  可设置 -XX:+ExplicitGCInvokesConcurrent 来做一次稍微高效点的GC ( 效果比Full GC要好些 )


-verbose:gc -XX:+PrintGCDetails  -XX:NativeMemoryTracking=detail -XX:MaxDirectMemorySize=100M 
-XX:+ExplicitGCInvokesConcurrent


 system.gc要点整理 

 unsafe要点 

 DirectByteBuffer监控 

上一篇     下一篇
NIO JMX BufferPool内存监控

AtomicInteger源码分析要点

unsafe要点

一行代码摧毁jvm

unix/linux基本理念和准则

自旋锁要点及简单实例