再介绍UnpooledDirectByteBuf之前,先了解一下NIO的DirectByteBuffer.
public static void main(String[] args) {
System.setProperty("java.jvm.name", "XXXX");
// UnpooledDirectByteBuf unpooledDirectByteBuf = (UnpooledDirectByteBuf) UnpooledByteBufAllocator.DEFAULT.directBuffer(9, 100);
ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.directBuffer(9, 100);
System.err.println(byteBuf);
}
通过debug我们发现,UnpooledByteBufAllocator底层是jdk的DirectByteBuffer
public class DirectByteBufferTest {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocateDirect(20);
for (byte i = 0; i < 5; i++){
buffer.put(i);
}
buffer.flip();
for (byte i = 0; i < 5; i++){
System.err.println(i);
}
}
}
测试结果如下:
0
1
2
3
4
long l = VM.maxDirectMemory();
System.err.println(l / 1024 / 1024);
long l1 = Runtime.getRuntime().maxMemory();
System.err.println(l1 / 1024/ 1024);
这块是加了一份Survivor区域。
-XX:MaxDirectMemorySize=1024M
DirectByteBuffer(int cap) { // package-private
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)) {
// 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;
}
上面还做了一些内存对齐的工作。。
Cleaner对象进行内存回收的缺点是存在滞后性。
注意这里分配内存的构造器也发生了变化,因为使用默认的构造器,会额外创建cleaner对象。
这也是netty底层优先使用的方法。
上面这几个方法创建的都是用户空间的内存,也就是直接内存,不是堆内存!
- 对于大内存有良好的伸缩性
- 明显提升了垃圾回收的停顿
- 在进程间可以共享,避免了虚拟机之间的复制