31

java.nio.ByteBuffer#duplicate() returns a new byte buffer that shares the old buffer's content. Changes to the old buffer's content will be visible in the new buffer, and vice versa. What if I want a deep copy of the byte buffer?

6 Answers 6

48

I think the deep copy need not involve byte[]. Try the following:

public static ByteBuffer clone(ByteBuffer original) {
       ByteBuffer clone = ByteBuffer.allocate(original.capacity());
       original.rewind();//copy from the beginning
       clone.put(original);
       original.rewind();
       clone.flip();
       return clone;
}
4
  • Why do I need to flip the clone? Then the limit is lower than my real capacity
    – Karussell
    Jun 16, 2012 at 13:23
  • 2
    The only thing not copied in this case is the mark, so just know that if you use mark it will be lost. Also, this function only copies from the beginning to the limit and the position of original is lost, I would suggest setting position = 0 and limit = capacity and storing them as temp vars to be reset on original and clone before returning. Also rewind discards the mark so using that is probably not a good idea. I will post an answer with a more complete method.
    – LINEMAN78
    Nov 20, 2012 at 3:01
  • 1
    Very useful, thanks. I think it would be better if you left the original ByteBuffer unchanged though, so int start = original.position() at the start, and original.position(start) at the end. Nov 19, 2013 at 22:11
  • Just have a chance to review this answer I made a few years ago. It is a good point about not to touch the position. If the original is reset to its initial position, should the clone be set to the same position as well? I expect people who want a clone want the clone be in position 0 so that it is ready for use right away, otherwise will get confused. I indeed expect the clone() method will set the original to the end position, but diff ppl has diff expectation. Perhaps its better to keep it simple, people who need a better solution can go for LINEMAN78's more comprehensive answer.
    – mingfai
    Jan 13, 2014 at 3:22
24

As this question still comes up as one of the first hits to copying a ByteBuffer, I will offer my solution. This solution does not touch the original buffer, including any mark set, and will return a deep copy with the same capacity as the original.

public static ByteBuffer cloneByteBuffer(final ByteBuffer original) {
    // Create clone with same capacity as original.
    final ByteBuffer clone = (original.isDirect()) ?
        ByteBuffer.allocateDirect(original.capacity()) :
        ByteBuffer.allocate(original.capacity());

    // Create a read-only copy of the original.
    // This allows reading from the original without modifying it.
    final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer();

    // Flip and read from the original.
    readOnlyCopy.flip();
    clone.put(readOnlyCopy);

    return clone;
}

If one cares for the position, limit, or order to be set the same as the original, then that's an easy addition to the above:

clone.position(original.position());
clone.limit(original.limit());
clone.order(original.order());
return clone;
4
  • 1
    Why not clone.put(readOnlyCopy) instead of the intermediate byte array?
    – seh
    Jan 27, 2014 at 19:34
  • @seh Because I was silly and did not see that method. Thanks for pointing it out.
    – jdmichal
    Jan 27, 2014 at 19:43
  • This is the best solution. It does not mutate the original contents and provides the cleanest ways to do the same thing. Oct 19, 2014 at 1:29
  • 1
    I tried this and have two comments: original.capacity() should probably be replaced with original.remaining(), if the backing buffer is not exactly equal to the number of characters in the buffer. Secondly, flip() is only necessary if original is in write mode. So I would not do this in the code, but rather require that the caller places the buffer in read mode. Sep 27, 2016 at 11:21
4

Based off of mingfai's solution:

This will give you an almost true deep copy. The only thing lost will be the mark. If orig is a HeapBuffer and the offset is not zero or the capacity is less than the backing array than the outlying data is not copied.

public static ByteBuffer deepCopy( ByteBuffer orig )
{
    int pos = orig.position(), lim = orig.limit();
    try
    {
        orig.position(0).limit(orig.capacity()); // set range to entire buffer
        ByteBuffer toReturn = deepCopyVisible(orig); // deep copy range
        toReturn.position(pos).limit(lim); // set range to original
        return toReturn;
    }
    finally // do in finally in case something goes wrong we don't bork the orig
    {
        orig.position(pos).limit(lim); // restore original
    }
}

public static ByteBuffer deepCopyVisible( ByteBuffer orig )
{
    int pos = orig.position();
    try
    {
        ByteBuffer toReturn;
        // try to maintain implementation to keep performance
        if( orig.isDirect() )
            toReturn = ByteBuffer.allocateDirect(orig.remaining());
        else
            toReturn = ByteBuffer.allocate(orig.remaining());

        toReturn.put(orig);
        toReturn.order(orig.order());

        return (ByteBuffer) toReturn.position(0);
    }
    finally
    {
        orig.position(pos);
    }
}
1
  • Why do you need the class name check when Buffer#isDirect() is available publicly?
    – seh
    Nov 20, 2012 at 15:50
3

One more simple solution

public ByteBuffer deepCopy(ByteBuffer source, ByteBuffer target) {

    int sourceP = source.position();
    int sourceL = source.limit();

    if (null == target) {
        target = ByteBuffer.allocate(source.remaining());
    }
    target.put(source);
    target.flip();

    source.position(sourceP);
    source.limit(sourceL);
    return target;
}
1

You'll need to iterate the entire buffer and copy by value into the new buffer.

1
  • 3
    There's an (optional) overload of the put method that does this for you though.
    – nos
    Jul 29, 2010 at 21:08
1

I believe this should supply a full deep copy, including the mark, "out-of-bounds" data, etc...just in case you need the most complete sandbox-safe carbon copy of a ByteBuffer.

The only thing it doesn't copy is the read-only trait, which you can easily get by just calling this method and tagging on a ".asReadOnlyBuffer()"

public static ByteBuffer cloneByteBuffer(ByteBuffer original)
{
    //Get position, limit, and mark
    int pos = original.position();
    int limit = original.limit();
    int mark = -1;
    try
    {
        original.reset();
        mark = original.position();
    }
    catch (InvalidMarkException e)
    {
        //This happens when the original's mark is -1, so leave mark at default value of -1
    }

    //Create clone with matching capacity and byte order
    ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity()) : ByteBuffer.allocate(original.capacity());
    clone.order(original.order());

    //Copy FULL buffer contents, including the "out-of-bounds" part
    original.limit(original.capacity());
    original.position(0);
    clone.put(original);

    //Set mark of both buffers to what it was originally
    if (mark != -1)
    {
        original.position(mark);
        original.mark();

        clone.position(mark);
        clone.mark();
    }

    //Set position and limit of both buffers to what they were originally
    original.position(pos);
    original.limit(limit);
    clone.position(pos);
    clone.limit(limit);

    return clone;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.