I made a change in the blogger configuration to ease the later work when blogging. It is possible that older entries are not correctly formatted.

Thursday 10 January 2008

Java NIO - Buffers

We will start the explanation of the Java NIO main classes by taking a look at buffers.

Buffers

The Buffers contain a fixed amount of data (obtained using the capacity() method). They have a number of useful methods, for example: mark, reset, clear, flip and rewind. mark remenbers a position to which on can come back by using reset.

Access methods for the buffers are the get() and put() methods (these can be absolute or relative, i.e either one specifies the position in the buffer to set or retrieve or one gets or retrieve the current element).

There are one type of Buffer for each of the main non Boolean primitive types ( plus one called the MappedByteBuffer used when using memory-mapped files). All these Buffer types are abstract but possess a factory for that type of Buffer in order to create one. Different methods exist for example in the case of a CharBuffer: allocate( int capacity), or wrap(char[] array ) which return CharBuffers either of the given capacity or containing the elements found in the array. Note: the changes to the underlying array will be seen in the buffer and vice versa. This type of buffer have a non direct access. In other words they have an array used to contain the data. using the method hasArray() allows you to check whether this Buffer is non direct or not.

A special case has to be explained that direct buffer are actually of type ByteBuffer and are created using the allocateDirect(in capacity) method. The ByteBuffer class also provides the possibility to create View Buffers. This allows the possibility of obtaining instances of other types of Buffers, e.g CharBuffer or IntBuffer without taking care of the problem of conversion. This is performed for example using the asCharBuffer() method.

Many methods of the Buffer classes return also buffer references. Thus you can perform sequence of actions on the buffer in a simple way. This is called invocation chaining.

Other methods can also create views on other buffers. These methods allow for example the duplication of a buffer (using the duplicate() method), its view as a read only buffer (using the asReadOnlyBuffer() method), or a view of only part of this buffer (using the slice()) method).