如何在Java中垃圾收集直接缓冲区 [英] How to garbage collect a direct buffer in Java
问题描述
我有一个内存泄漏,我已经隔离到错误配置的直接字节缓冲区.
I have a memory leak that I have isolated to incorrectly disposed direct byte buffers.
ByteBuffer buff = ByteBuffer.allocateDirect(7777777);
GC会收集包含这些缓冲区但不处理缓冲区本身的对象.如果我实例化包含缓冲区的瞬态对象足够多,则会收到以下令人鼓舞的消息:
The GC collects the objects that harbor these buffers but does not dispose of the buffer itself. If I instantiate enough of the transient objects containing buffers, I get this encouraging message:
java.lang.OutOfMemoryError: Direct buffer memory
我一直在寻找这个问题,显然
I have been searching up this problem and apparently
buff.clear();
和
System.gc();
不起作用.
推荐答案
我怀疑您的应用程序某个地方对ByteBuffer实例进行了引用,从而阻止了对其的垃圾回收.
I suspect that somewhere your application has a reference to the ByteBuffer instance(s) and that is preventing it from being garbage collected.
直接ByteBuffer的缓冲存储器分配在普通堆之外(这样GC不会移动它!).但是,ByteBuffer API没有提供显式处理/取消分配缓冲区的方法.因此,我假设垃圾回收器将执行此操作……一旦它确定不再引用ByteBuffer对象.
The buffer memory for a direct ByteBuffer is allocated outside of the normal heap (so that the GC doesn't move it!!). However, the ByteBuffer API provides no method for explicitly disposing of / deallocating a buffer. So I assume that the garbage collector will do it ... once it determines that the ByteBuffer object is no longer referenced.
这篇关于如何在Java中垃圾收集直接缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!