ByteBuffer AsReadOnlyBuffer And Duplicate Views
Share buffer bytes across independent cursors with duplicate() and hand untrusted callers immutable views via asReadOnlyBuffer() safely.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.