Java ByteBuffer Clear free(ByteBuffer byteBuffer)

Here you can find the source of free(ByteBuffer byteBuffer)

Description

Try deallocate direct byte buffer, do nothing if buffer is not direct

License

Open Source License

Declaration

public static boolean free(ByteBuffer byteBuffer) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Method;
import java.nio.ByteBuffer;

public class Main {
    /**/*from ww  w  . j  av a 2 s.  c o  m*/
     * Try deallocate direct byte buffer, do nothing if buffer is not direct
     */
    public static boolean free(ByteBuffer byteBuffer) {
        if (byteBuffer == null || !byteBuffer.isDirect()) {
            return false;
        }

        //call ((DirectBuffer)byteBuffer).cleaner().clean() by reflection
        try {
            Method getCleanerMethod = byteBuffer.getClass().getDeclaredMethod("cleaner");
            getCleanerMethod.setAccessible(true);
            Object cleaner = getCleanerMethod.invoke(byteBuffer);
            if (cleaner != null) {
                Method cleanMethod = cleaner.getClass().getDeclaredMethod("clean");
                cleanMethod.setAccessible(true);
                cleanMethod.invoke(cleaner);
                return true;
            }
        } catch (Exception e) {
            return false;
        }

        return false;
    }
}

Related

  1. clearRemainingFrame(ByteBuffer buffer, int position)
  2. clearString(ByteBuffer buffer)
  3. fillBuffer(ReadableByteChannel channel, ByteBuffer buf, boolean clear)
  4. free(ByteBuffer buffer)
  5. free(ByteBuffer buffer)
  6. freeDB(ByteBuffer buffer)
  7. freeMemory(ByteBuffer buffer)