如何创建 DirectByteBuffer
通过 ByteBuffer.allocateDirect(int capacity) 方法创建
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
源码分析
分析 DirectByteBuffer 构造函数,创建 DirectByteBuffer 可分为三步:
- 计算需要分配的内存大小
- 分配内存,保存内存地址
- 创建内存回收器
DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap);
// 是否需要内存分页对齐
boolean pa = VM.isDirectMemoryPageAligned();
// 获取内存分页大小
int ps = Bits.pageSize();
// 计算需要分配的内存大小:如果需要分页对齐则加上1个分页
long size = Math.max(1L, (long)cap + (pa ? ps : 0));
Bits.reserveMemory(size, cap);
long base = 0;
try {
// 分配内存
base = UNSAFE.allocateMemory(size);
} catch (OutOfMemoryError x) {
Bits.unreserveMemory(size, cap);
throw x;
}
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;
}