我有一个内存泄漏问题,它被隔离到了错误地处理直接字节缓冲区。
ByteBuffer buff = ByteBuffer.allocateDirect(7777777);
GC会收集这些缓冲区的对象,但不会处理缓冲区本身。如果我实例化足够多的包含缓冲区的瞬态对象,我会得到这个令人鼓舞的消息:
java.lang.OutOfMemoryError: Direct buffer memory
我一直在搜索这个问题,显然
buff.clear();
和
System.gc();
都没有用。
我有一个内存泄漏问题,它被隔离到了错误地处理直接字节缓冲区。
ByteBuffer buff = ByteBuffer.allocateDirect(7777777);
GC会收集这些缓冲区的对象,但不会处理缓冲区本身。如果我实例化足够多的包含缓冲区的瞬态对象,我会得到这个令人鼓舞的消息:
java.lang.OutOfMemoryError: Direct buffer memory
我一直在搜索这个问题,显然
buff.clear();
和
System.gc();
都没有用。
我怀疑你的应用程序在某个地方引用了ByteBuffer实例,这阻止了它被垃圾回收。
直接ByteBuffer的缓冲区内存是在正常堆之外分配的(以便GC不会移动它!)。然而,ByteBuffer API没有提供显式释放/删除缓冲区的方法。因此,我认为垃圾收集器会在确定ByteBuffer对象不再被引用时进行处理。
一旦DBB到达引用队列并运行终结器,它将被解除分配。然而,由于我们不能依赖终结器运行,因此我们可以使用反射手动调用其“清理器”。
使用反射:
/**
* DirectByteBuffers are garbage collected by using a phantom reference and a
* reference queue. Every once a while, the JVM checks the reference queue and
* cleans the DirectByteBuffers. However, as this doesn't happen
* immediately after discarding all references to a DirectByteBuffer, it's
* easy to OutOfMemoryError yourself using DirectByteBuffers. This function
* explicitly calls the Cleaner method of a DirectByteBuffer.
*
* @param toBeDestroyed
* The DirectByteBuffer that will be "cleaned". Utilizes reflection.
*
*/
public static void destroyDirectByteBuffer(ByteBuffer toBeDestroyed)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
Preconditions.checkArgument(toBeDestroyed.isDirect(),
"toBeDestroyed isn't direct!");
Method cleanerMethod = toBeDestroyed.getClass().getMethod("cleaner");
cleanerMethod.setAccessible(true);
Object cleaner = cleanerMethod.invoke(toBeDestroyed);
Method cleanMethod = cleaner.getClass().getMethod("clean");
cleanMethod.setAccessible(true);
cleanMethod.invoke(cleaner);
}
ByteBuffer
文档中提到:
可以通过调用这个类的
allocateDirect
工厂方法来创建一个直接字节缓冲区。由此方法返回的缓冲区通常具有比非直接缓冲区更高的分配和释放成本。直接缓冲区的内容可能驻留在正常垃圾回收堆之外,因此它们对于应用程序的内存占用可能不明显。因此,建议仅为长时间存在、受底层系统本地I/O操作影响的大型缓冲区分配直接缓冲区。一般情况下,只有在直接缓冲区能够提供可衡量的程序性能增益时才最好分配直接缓冲区。
特别是,“可能驻留在正常垃圾回收堆之外”这句话似乎与你的例子相关。
public static void destroyBuffer(Buffer buffer) {
if(buffer.isDirect()) {
try {
if(!buffer.getClass().getName().equals("java.nio.DirectByteBuffer")) {
Field attField = buffer.getClass().getDeclaredField("att");
attField.setAccessible(true);
buffer = (Buffer) attField.get(buffer);
}
Method cleanerMethod = buffer.getClass().getMethod("cleaner");
cleanerMethod.setAccessible(true);
Object cleaner = cleanerMethod.invoke(buffer);
Method cleanMethod = cleaner.getClass().getMethod("clean");
cleanMethod.setAccessible(true);
cleanMethod.invoke(cleaner);
} catch(Exception e) {
throw new QuartetRuntimeException("Could not destroy direct buffer " + buffer, e);
}
}
}
/**
* Sun specific mechanisms to clean up resources associated with direct byte buffers.
*/
@SuppressWarnings("unchecked")
private static final Class<? extends ByteBuffer> SUN_DIRECT_BUFFER = (Class<? extends ByteBuffer>) lookupClassQuietly("sun.nio.ch.DirectBuffer");
private static final Method SUN_BUFFER_CLEANER;
private static final Method SUN_CLEANER_CLEAN;
static
{
Method bufferCleaner = null;
Method cleanerClean = null;
try
{
// operate under the assumption that if the sun direct buffer class exists,
// all of the sun classes exist
if (SUN_DIRECT_BUFFER != null)
{
bufferCleaner = SUN_DIRECT_BUFFER.getMethod("cleaner", (Class[]) null);
Class<?> cleanClazz = lookupClassQuietly("sun.misc.Cleaner");
cleanerClean = cleanClazz.getMethod("clean", (Class[]) null);
}
}
catch (Throwable t)
{
t.printStackTrace();
}
SUN_BUFFER_CLEANER = bufferCleaner;
SUN_CLEANER_CLEAN = cleanerClean;
}
public static void releaseDirectByteBuffer(ByteBuffer buffer)
{
if (SUN_DIRECT_BUFFER != null && SUN_DIRECT_BUFFER.isAssignableFrom(buffer.getClass()))
{
try
{
Object cleaner = SUN_BUFFER_CLEANER.invoke(buffer, (Object[]) null);
SUN_CLEANER_CLEAN.invoke(cleaner, (Object[]) null);
}
catch (Throwable t)
{
logger.trace("Exception occurred attempting to clean up Sun specific DirectByteBuffer.", t);
}
}
}
现有答案中缺少许多注意事项,例如在JDK 9+下运行时模块描述符必须包含requires jdk.unsupported
、在JDK 16+下由于强制执行强封装而无法访问MappedByteBuffer.cleaner()
,在JDK 7-16下使用SecurityManager
时的要求等。我在这里详细介绍了所有细节: