Java NIO – Buffers

Buffers are containers of data. They store bytes and other primitive java types in arrays and allow processes to read and write bytes onto them. Buffers have three important properties. 1. Position – identifies the index where the next byte will be written or read. 2. Limit – identifies the index where there is no byte for reading or where byte should not be written. 3. Capacity – identifies the count of bytes that can be accomodated in the buffer.

Byte Buffer Creation

Byte Buffer – a byte buffer is a buffer of bytes.one way to create byte buffer is by allocating memory in the heap space. The call below allocates 10 bytes to the buffer.

a byte buffer may also be created by allocating memory outside the jvm and directly in the os memory. in the case of direct allocation the free memory available in the jvm does not change

a last way to create byte buffer is to create a wrapper around an existing byte array. It points to the data of the wrapped array and hence creates just a view.

Operations

Let us look at how the position, limit and capacity are affected by the various operations on the buffer

we write 1 char or two bytes to the buffer. The put method can be used to ‘put’ or write values in the buffer. The values are put at the current position. various variants of the put methods are available and they can write the various primitive types.

as we expected the char writes two bytes into the buffer and hence increments the position by 2. (0,1). this implies that the next byte will be written at index 2 (remember index starts from 0). Next, lets write an int

int occupies 4 bytes. The position is at 6. lets go back to 0 and start reading

we are now trying to read the bytes that we have written. flip() takes us to the start of the buffer and also sets the limit to 6 so that we know that we can read upto the 6 th element (0 to 5). We read the first two bytes

This prints a. we planned to read all bytes that we had written but we want to write another int now. since we have already read the char, lets compact the buffer by shifting the bytes that we have already read out.

so now the first four bytes are occupied by the int that we had originally written and the next six bytes are available for writing we write another int

lets start reading

But what if we want to read the same buffer again?

lets mark this position and then read the next int and go back to the marked position

The clear() functions clears the buffer, marks position as start of buffer and marks limit = capacity =10;

Leave a Comment