前面介绍过Java Buffer使用的内存分堆内内存(Heap)和堆外内存(No Heap),本文将介绍DirectBuffer的实现原理,以DirectByteBuffer为例。
DirectByteBuffer
DirectByteBuffer是ByteBuffer的一个实现。如果需要实例化一个DirectByteBuffer,可以使用java.nio.ByteBuffer#allocateDirect()
。
1 2 3
| public static ByteBuffer allocateDirect(int capacity) { return new DirectByteBuffer(capacity); }
|
内存申请
先来看一下DirectByteBuffer是如何构造,如何申请与释放内存的。下面是 DirectByteBuffer 的构造器代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| DirectByteBuffer(int cap) { super(-1, 0, cap, cap); boolean pa = VM.isDirectMemoryPageAligned(); int ps = Bits.pageSize(); 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)) { address = base + ps - (base & (ps - 1)); } else { address = base; } cleaner = Cleaner.create(this, new Deallocator(base, size, cap)); att = null; }
|