Performs a deep copy on a byte buffer. - Java java.nio

Java examples for java.nio:ByteBuffer Copy

Description

Performs a deep copy on a byte buffer.

Demo Code


//package com.java2s;

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

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

    /**/*from  ww  w  .j av  a  2  s . co m*/
     * 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 Tutorials