public static ByteBuffer allocateDirect(int capacity) { return new DirectByteBuffer(capacity); }
DirectByteBuffer 的代码节选:
DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap, false); Bits.reserveMemory(cap); int ps = Bits.pageSize(); long base = 0; try { base = unsafe.allocateMemory(cap + ps); } catch (OutOfMemoryError x) { Bits.unreserveMemory(cap); throw x; } unsafe.setMemory(base, cap + ps, (byte) 0); if (base % ps != 0) { // Round up to page boundary address = base + ps - (base & (ps - 1)); } else { address = base; } cleaner = Cleaner.create(this, new Deallocator(base, cap));
}
java使用的是本地方法在管理相对应的内存: public native long allocateMemory(long _long); public native void setMemory(long _long, long _long1, byte _byte); public native void copyMemory(long _long, long _long1, long _long2); public native void freeMemory(long _long);