public static void main(String[] args) throws Exception {
ByteBufAllocator byteBufAllocator = new UnpooledByteBufAllocator(false);
for (int i = 0; i < 1000; i++) {
ByteBuf buffer = byteBufAllocator.directBuffer(20 * 1024 * 1024);
System.out.println("分配了 " + 20 * (i + 1) + " MB");
Thread.sleep(30);
}
}
使用jvm参数:
-Xmx200m -Xms200m
发现一会内存就爆了:
image.png
这个是为什么呢,UnpooledByteBufAllocator不应该是自动回收的吗?
改成
ByteBufAllocator byteBufAllocator = new UnpooledByteBufAllocator(false,false,false);
这样就好了,就不爆内存了。
原来构造函数的第三参数指定了是否使用Cleaner,指定为false的情况下,才会回收堆外内存。
而堆外内存的回收是依赖Cleaner的。
image.png
image.png