Interface DirectBufferDeallocator

  • All Known Implementing Classes:
    DirectBufferDeallocator.NoOp

    public interface DirectBufferDeallocator
    The combination of:
    • Missing proper DirectByteBuffer public API interface type,
    • Missing deallocate() possibility for direct ByteBuffers,
    • sun.misc.Cleaner package change with Java 9,
    • modules with Java 9 AND java.base not exporting its stuff so that halfway proper workarounds for the JDK design errors could be created using reflection without forcing special vm arguments on everyone wanting to use the library
    leave only one sanity-preserving way to handle explicit deallocation of memory directly allocated by ByteBuffer.allocateDirect(int):

    ---

    This type handles explicit deallocation of memory allocated by direct ByteBuffers created via ByteBuffer.allocateDirect(int).
    The default implementation is a no-op to maintain compatibility accross the Java 8-9 transition.

    The required approach for a functional implementation would be:

    For JDK 8:

     // compensate missing proper typing in JDK
     if(!(directByteBuffer instanceof sun.nio.ch.DirectBuffer))
     return; // or throw exceptionsun.misc.Cleaner cleaner = ((sun.nio.ch.DirectBuffer)directByteBuffer).cleaner();
     // cleaner can be null
     if(cleaner != null)
     cleaner.clean();
     }
     }

    For JDK 9(+)

     // compensate missing proper typing in JDK
     if(!(directByteBuffer instanceof sun.nio.ch.DirectBuffer))
     return; // or throw exceptionjdk.internal.ref.Cleaner cleaner = ((sun.nio.ch.DirectBuffer)directByteBuffer).cleaner();
     // cleaner can be null
     if(cleaner != null)
     cleaner.clean();
     }
     }
    Also see: http://stackoverflow.com/questions/8462200/examples-of-forcing-freeing-of-native-memory-direct-bytebuffer-has-allocated-us