堆外内存申请和释放:
堆外内存时不受jvm管理,gc算法不能被回收的。
如何申请和释放?
1. unsafe类
我们可以使用unsafe类来进行申请和释放:
申请:
// 分配 10M 堆外内存
long address = unsafe.allocateMemory(10 * 1024 * 1024);
释放:unsafe.freeMemory()
使用:
private static Unsafe unsafe = null;
static {
try {
Field getUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
getUnsafe.setAccessible(true);
unsafe = (Unsafe) getUnsafe.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
unsafe通过jni来进行调用,调用到c语言的unsafe_allocateMemory。
其实还是调用c的函数:malloc来申请内存
释放的c函数:free
2. NIO中也会有堆外内存的申请
// 分配 10M 堆外内存
ByteBuffer buffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
跟一下源码: 底层调用的是DirectByteBuffer
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity)