Java ByteBuffer Copy copy(ByteBuffer bb, boolean forceDirect)

Here you can find the source of copy(ByteBuffer bb, boolean forceDirect)

Description

Performs a deep copy on a byte buffer.

License

Open Source License

Parameter

Parameter Description
bb source byte buffer
forceDirect force copy to be a direct ByteBuffer

Return

deep copy of source buffer

Declaration

public static ByteBuffer copy(ByteBuffer bb, boolean forceDirect) 

Method Source Code

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

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    private static final int DIRECT_THRESHOLD = 10240;

    /**/*from   w  w  w. j ava2s . c om*/
     * Performs a deep copy on a byte buffer. The resulting byte buffer will have
     * the same position, byte order and visible bytes as the original byte buffer.
     * If the source buffer is direct, the copied buffer will be direct, too.
     * 
     * Any changes in one buffer won't be visible to the other, i.e. the two
     * buffers will be entirely independent from another.
     * 
     * The position and limit of the original buffer won't change after this
     * operation.
     * 
     * @param bb source byte buffer
     * @param forceDirect force copy to be a direct ByteBuffer
     * @return deep copy of source buffer
     */
    public static ByteBuffer copy(ByteBuffer bb, boolean forceDirect) {
        int capacity = bb.limit();
        int pos = bb.position();
        ByteOrder order = bb.order();
        ByteBuffer copy;

        if (bb.isDirect() || forceDirect) {
            copy = ByteBuffer.allocateDirect(capacity);
        } else {
            copy = ByteBuffer.allocate(capacity);
        }

        bb.rewind();

        copy.order(order);
        copy.put(bb);
        copy.position(pos);

        bb.position(pos);

        return copy;
    }

    public static ByteBuffer copy(ByteBuffer bb) {
        return copy(bb, false);
    }

    public static ByteBuffer allocate(int size) {
        // allocateDirect is pretty slow when used frequently, use it for larger
        // buffers only
        if (size > DIRECT_THRESHOLD) {
            return ByteBuffer.allocateDirect(size);
        } else {
            try {
                return ByteBuffer.allocate(size);
            } catch (OutOfMemoryError ex) {
                // not enough space in the heap, try direct allocation instead
                return ByteBuffer.allocateDirect(size);
            }
        }
    }
}

Related

  1. copy(ByteBuffer buf)
  2. copy(ByteBuffer buffer)
  3. copy(ByteBuffer buffer)
  4. copy(ByteBuffer buffer)