How to garbage collect a direct buffer in Java

前端 未结 6 1807
遥遥无期
遥遥无期 2020-12-05 00:02

I have a memory leak that I have isolated to incorrectly disposed direct byte buffers.

ByteBuffer buff = ByteBuffer.allocateDirect(7777777);

The GC colle

6条回答
  •  暖寄归人
    2020-12-05 00:51

    Here is a refined implementation that will work for any direct buffer:

    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);
            }
        }
    }
    

提交回复
热议问题