Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java ByteBuffer.slice: shared storage and independent cursors

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

ByteBuffer.slice creates a new view over the selected remaining bytes, with independent position and limit but shared content.

Separate cursor independence from data independence

Moving the slice position does not move the parent's position. Writing through the slice does change the parent's bytes. A slice is useful for parsing a framed region without copying it, but it is unsafe as a long-lived snapshot when the parent buffer is reused for more input.

The fixture selects bytes at parent indexes one through three, writes into the slice, and observes the parent changed while its cursor stays at one. flip and compact manage buffer reuse; those operations can make a retained slice point at different logical data.

Copy at ownership boundaries

If an asynchronous task needs stable bytes after the read loop continues, copy the selected range or transfer exclusive ownership of the backing buffer. Array copying addresses the same distinction for arrays; a read-only view prevents writes through that view but still reflects writes through other aliases.

Working program

Java
import java.nio.ByteBuffer;
import java.util.Arrays;

public class ManifestFieldSlice {
    public static void main(String[] args) {
        ByteBuffer parent = ByteBuffer.wrap(new byte[] {10, 20, 30, 40, 50});
        parent.position(1);
        parent.limit(4);
        ByteBuffer field = parent.slice();
        field.put(0, (byte) 82);
        field.position(2);
        System.out.println(Arrays.toString(parent.array()));
        System.out.println("parent=" + parent.position() + ", field=" + field.position());
    }
}

Output

Output
[10, 82, 30, 40, 50]
parent=1, field=2

Cost and ownership

Creating a slice is O(1) and does not copy bytes. The memory retained by the view can include the parent's entire backing storage; a small long-lived slice can therefore keep a large parent allocation reachable.

Common Mistakes

  • Do not call a slice a snapshot.
  • Do not assume parent and slice share cursor positions.
  • Do not retain a slice after the backing buffer is repurposed without an ownership rule.

Read next

Java ByteBuffer flip and compact: preserve an incomplete frame, Java ByteBuffer byte order: decode the protocol before reading integers, Java array copies: new slots can still point at old objects, Java file channels: buffer positions and partial transfers.

java
io
bytebuffer-slice-ownership
Storage details