Java - Read-Only Buffers


A buffer can be read-only or read-write.

The properties of a read-only buffer such as its position, limit, and mark can be changed, but not its data.

You can get a read-only buffer by calling the asReadOnlyBuffer().

To check if a buffer is read-only by calling the isReadOnly() method as follows:

// Create a buffer that is read-write by default
ByteBuffer bb = ByteBuffer.allocate(1024);
boolean readOnly = bb.isReadOnly(); // Assigns false to readOnly

// Get a read-only buffer
ByteBuffer bbReadOnly = bb.asReadOnlyBuffer();
readOnly = bbReadOnly.isReadOnly(); // Assigns true to readOnly

The read-only buffer returned by the asReadOnlyBuffer() method is a different view of the same buffer.

The new read-only buffer shares data with its original buffer.

Any modifications to the contents of the original buffer are reflected in the read-only buffer.

A read-only buffer has the same value of position, mark, limit, and capacity as its original buffer at the time of creation and it maintains them independently afterwards.