DirectByteBuffer implements ByteBuffer { public void free() { try { java.lang.reflect.Field cleanerField = byteBuffer.getClass().getDeclaredField("cleaner"); cleanerField.setAccessible(true); sun.misc.Cleaner cleaner = (sun.misc.Cleaner) cleanerField.get(byteBuffer); cleaner.clean(); } catch (Exception e) { throw new Error(e); } } DirectByteBuffer(final int capacity); static sun.misc.Unsafe getUnsafe(); void get(int position, byte[] destination, int offset, int length); void put(int position, byte[] source, int offset, int length); void free();  }
@Test public void free() { int size = 1024 * 1024 * 2; byte[] bytes = new byte[size]; random.nextBytes(bytes); buffer.free(); }