Java Reference
In-Depth Information
The diagram illustrates a byte buffer with a view buffer of type IntBuffer mapped to the first 8 bytes,
and a view buffer of type CharBuffer mapped to the last 12 bytes. All you need to do to achieve this
is to ensure the position of the byte buffer is set appropriately before you create each view buffer.
Duplicating and Slicing Buffers
You can duplicate any of the buffers we have discussed by calling the duplicate() method for a
buffer. The method returns a reference to a buffer with the same type as the original, which shares the
contents. The duplicate buffer initially has the same capacity, position, and limit as the original.
However, although changes to the contents of the duplicate will be reflected in the original - and vice
versa, each buffer's position and limit are independent of the other. One use for a duplicate buffer is
when you want to access different parts of the buffer's contents concurrently. You can retrieve data from
a duplicate buffer without affecting the original buffer in any way.
capacity = 20
position = 2
limit = 12
Buffer duplicated from buf
position = 2
buf .duplicated()
limit = 12
Original Buffer buf
capacity = 20
buf .slice()
Buffer sliced from buf
position = 0
limit = 10
capacity = 10
Duplicating and Slicing a Buffer
Thus a duplicate buffer is not really a new buffer in memory. It is just a new object that provides an
alternative route to accessing the same block of memory that is being used to buffer the data. The
duplicate() method returns a reference of a new object of the same type as the original, but has no
independent data storage. It merely shares the memory that belongs to the original buffer object but
with independent position and limit values.
Search WWH ::




Custom Search