Working with Buffers in Java
NIO (New Input Output) streams in Java have been introduced keeping in mind the higher performance demands of new web-based applications. The java.nio class has been formed basing Java Buffers therefore the concept of Buffers becomes very important in this regard. In simple words, a buffer is a temporary or permanent storage or container of data. Buffers act as intermediate storage facilities when data is being moved from one part of a program to another.
Features of the Buffer Class
- As mentioned before, buffers are containers that contain a fixed amount of data. Buffers are mostly temporary but, in some cases, the scope of a buffer can run until the end of a program.
- Buffers and channels work together to facilitate inputs and outputs. Channels are the ports through which input and output transfers take place. The final destination of these channels are Buffers.
- All outbound data that we want to send are initially stored in buffers. These buffers pass the data to out channels.
- For incoming data transfers, the data is stored in a buffer initially. The buffer then connects to an in channel to pass on the data.
- This systemic flow of data using buffers as a mode of transportation is key to efficient data handling under NIO APIs.
In the hierarchy table, the generic Buffer class sits at the top. It is followed by specific type buffers as the next layer. Some of the specific buffers are CharBuffer, IntBuffer, DoubleBuffer, ShortBuffer, LongBuffer, FloatBuffer, and ByteBuffer. The MappedByteBuffer hierarchically sits below the ByetBuffer.
Components of a Generic Buffer
A Buffer is an array of primitive data elements wrapped in an object. Some of the components of a Buffer are as follows:
- Capacity – This determines the length of a Buffer (maximum number of elements). The capacity of a buffer is final and it cannot be modified throughout its life.
- Limit – Limit tells you the number of live elements in the buffer.
- Position – This returns the index of the next element in line to be read.
- Mark – This is a highlighted position in the buffer.
If you want to create a buffer of type character and a fixed size:
CharBuffer charBuffer = CharBuffer.allocate (100); //This buffer can hold upto 100 characters