JVM参数 -XX:MaxDirectMemorySize=1024M 来设置可以使用的堆外内存大小。
代码中可以使用VM工具类获取
VM.maxDirectMemory()
DirectByteBuffer源码分析
DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap);
//是否按页对齐
boolean pa = VM.isDirectMemoryPageAligned();
//内存页大小默认4096
int ps = Bits.pageSize();
long size = Math.max(1L, (long)cap + (pa ? ps : 0));
//增加内部计数器-超量报oom异常
Bits.reserveMemory(size, cap);
long base = 0;
try {
//分配内存空间
base = unsafe.allocateMemory(size);
} catch (OutOfMemoryError x) {
//减少计数器的值
Bits.unreserveMemory(size, cap);
throw x;
}
//把内存快都设置为0
unsafe.setMemory(base, size, (byte) 0);
if (pa && (base % ps != 0)) {
// Round up to page boundary
address = base + ps - (base & (ps - 1));
} else {
//内存指针
address = base;
}
//释放器
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
att = null;
}
private static class Deallocator
implements Runnable
{
private static Unsafe unsafe = Unsafe.getUnsafe();
private long address;
private long size;
private int capacity;
private Deallocator(long address, long size, int capacity) {
assert (address != 0);
//内存地址
this.address = address;
//大小
this.size = size;
this.capacity = capacity;
}
public void run() {
//释放内存
unsafe.freeMemory(address);
address = 0;
//更新计数器
Bits.unreserveMemory(size, capacity);
}
}
Put值通过address+index还计算出内存位置,调用unsafe直接赋值。
public ByteBuffer put(byte x) {
//unsafe.putBytes(address + (position++), x);
unsafe.putByte(ix(nextPutIndex()), ((x)));
return this;
}