ByteBuffer AsReadOnlyBuffer And Duplicate Views

Share buffer bytes across independent cursors with duplicate() and hand untrusted callers immutable views via asReadOnlyBuffer() safely.

JavaSecurity Boundaries

Code

snippet
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.charset.StandardCharsets;

public class BufferViewBoundaries {

    public static void main(String[] args) {
        ByteBuffer mutable = ByteBuffer.wrap("TOKEN-42".getBytes(StandardCharsets.US_ASCII));

        // duplicate() creates an independent cursor sharing the same backing bytes
        ByteBuffer cursor = mutable.duplicate();
        cursor.position(6);
        System.out.println("cursor pos=" + cursor.position() + " mutable pos=" + mutable.position());

        // asReadOnlyBuffer() prevents writes and hides the backing array (hasArray() is false)
        ByteBuffer readOnly = mutable.asReadOnlyBuffer();
        System.out.println("isReadOnly=" + readOnly.isReadOnly() + " hasArray=" + readOnly.hasArray());

        // Mutations on the original buffer remain visible through the shared read-only view
        mutable.put(6, (byte) '9');
        byte[] seen = new byte[readOnly.remaining()];
        readOnly.get(seen);
        System.out.println("readOnly sees: " + new String(seen, StandardCharsets.US_ASCII));

        try {
            readOnly.put(0, (byte) 'X');
        } catch (ReadOnlyBufferException ex) {
            System.out.println("write blocked: " + ex.getClass().getSimpleName());
        }
    }
}

Annotated execution — ByteBuffer AsReadOnlyBuffer And Duplicate Views

Everything happens inside the class BufferViewBoundaries and the function main.

Points of care

  • Executes cleanly on stock toolchain features alone — no extra dependencies.

Putting it to use

Core invocation interface specifies public static void main(String[] args)

The file’s steps show up in the output as cursor pos=, isReadOnly=, readOnly sees:.

Core lines

ByteBuffer mutable = ByteBuffer.wrap("TOKEN-42".getBytes(StandardCharsets.US_ASCII));
ByteBuffer readOnly = mutable.asReadOnlyBuffer();
byte[] seen = new byte[readOnly.remaining()];

Interactive Tools for This Topic

FAQ

What does ByteBuffer AsReadOnlyBuffer And Duplicate Views print when run?
Running the file directly is enough — expect labeled output lines such as `cursor pos=`, `isReadOnly=`, `readOnly sees:`.