What is an NIO Buffer?

A buffer is used to transfer data between channels.

Internal state

Internally, a buffer is an array of data, where the type is determined by the subclass of java.nio.Buffer that is used: ShortBuffer, IntBuffer, FloatBuffer, DoubleBuffer, LongBuffer, CharBuffer and ByteBuffer.

A buffer maintains three essential properties: capacity, limit and position. Look at the example below for how these properties behave.

  • capacity: is the number of elements the buffer can contain. Once a buffer is allocated, its capacity never changes.

  • limit: the index of the first element that should not be read or written. In other words, elements are usable and can be read up to the index limit-1. For writing, the limit is typically equal to the capacity of the Buffer.
  • position: the index of the next element to be read or written. It is never greater than the limit.

    Creating Buffers

    You can’t directly create Buffers using a constructor.

    Example:

       // allocates memory that can contain 128 bytes
       ByteBuffer byteBuffer = ByteBuffer.allocate(128);
       // prints out 128
       System.out.println(byteBuffer.capacity());
     
       // allocates memory that can contain 128 integers
       IntBuffer intBuffer = IntBuffer.allocate(128);
       // prints out 128
       System.out.println(intBuffer.capacity());
    
  • You can also create a view on an existing ByteBuffer. The two buffers, the original and the view will operate on the same memory, so changing in one buffer will have direct effect in the other one.

    Example:

       // allocates memory that can contain 128 bytes
       ByteBuffer byteBuffer = ByteBuffer.allocate(128);
       // prints out 128
       System.out.println(byteBuffer.capacity());
    
       // Create an intBuffer view on the byteBuffer
       IntBuffer intBuffer = byteBuffer.asIntBuffer();
       // prints out 32, because 128 bytes is 32 integers of 4 bytes each
       System.out.println(intBuffer.capacity());
    
  • To create a Buffer from an existing array, use the wrap method. Changing the original array will change the Buffer.

    WrapExample.java:

    import java.nio.*;
     
    public class WrapExample
    {
       public static void main(String []args) {
          long la[] = { 10, 20, 30, 40 };  
          LongBuffer lb = LongBuffer.wrap(la);
     
          System.out.println("LongBuffer before changing original array");
          printBuffer(lb);
     
          // change the original array
          la[2] = 123456;
     
          System.out.println("LongBuffer after changing original array");
          printBuffer(lb);
       }
       
       public static void printBuffer(LongBuffer lb) {
          for (int i=0; i<lb.limit(); i++) {
             System.out.print(lb.get(i) + " ");
          }
          System.out.println();
       }
    }
    

    Reading/writing from and to a Buffer

    To read and write values from a buffer, you use that buffer’s specific get and put methods, that you can use in relative or absolute mode.

    The following example creates a CharBuffer and writes data to it.

    CharBufferTest.java:

    import java.nio.*;
     
    public class CharBufferTest 
    {
       public static void main(String []args) {
          CharBuffer cb = CharBuffer.allocate(10);
     
          cb.put('a'); 	// use relative put
          cb.put(3, 'b');	// use absolute put
          cb.put('c');	// use relative put
    
          printBuffer(cb);
       }
      
       public static void printBuffer(CharBuffer cb) {
          for (int i=0; i<cb.limit(); i++) {
             System.out.print(cb.get(i) + " ");
          }
          System.out.println();
       }
    } 
    

    outputs:

    a c   b
    

    Buffer Operations

    • flip(): Sets the limit to the current position and the position to zero. This method is typically used after a channel-read (put-operations in Buffer terms) and before a channel-write (get-operations in Buffer terms).

    Example buffer:
     
                          position     limit
                             |           |
           +---+---+---+---+---+---+---+
           | 2 | 4 | 3 | 9 | 0 | 0 | 0 |
           +---+---+---+---+---+---+---+
     
    After flip():
     
          position         limit
             |               |
           +---+---+---+---+---+---+---+
           | 2 | 4 | 3 | 9 | 0 | 0 | 0 |
           +---+---+---+---+---+---+---+
     
    Typical usage:
     
       inChannel.read(buffer);      // transfers data from the channel to the buffer
       flip();                      // prepares buffer for relative get-operations
       outChannel.write(buffer);    // transfers data from the buffer to the channel
    
  • clear(): Sets the limit to the Buffer’s capacity and the position to zero. This method is typically used after a channel-write (get-operations in Buffer terms) and before a channel-read (put-operations in Buffer terms).
    Example buffer that was just used by an out channel:
     
                          position
                           limit
                             |
           +---+---+---+---+---+---+---+
           | 2 | 4 | 3 | 9 | 0 | 0 | 0 |
           +---+---+---+---+---+---+---+
     
    After clear():
     
         position                      limit
             |                           |
           +---+---+---+---+---+---+---+
           | 2 | 4 | 3 | 9 | 0 | 0 | 0 |
           +---+---+---+---+---+---+---+
      
    Typical usage:
      
       outChannel.write(buffer);    // transfers data from the buffer to the channel
       clear();                     // prepares buffer for relative put-operations
       inChannel.read(buffer);      // transfers data from the channel to the buffer
    
  • rewind(): Sets the position to zero
  • position(int): with this method, you can assign a new index to the position. If the position is larger than the current limit, an IllegalArgumentException is thrown.
  • limit(int): with this method, you can assign a new index to the limit. The position is set to this limit if it is larger (the position is never larger than the limit).

    Here is an example of the different operations.

    Main.java:

    import java.nio.*;
     
    public class Main
    {
       public static void main(String []args) {
          ByteBuffer bb = ByteBuffer.allocate(10);
     
          printVars("Initial state", bb);
     
          bb.put((byte) 1);
          printVars("bb.put((byte) 1)", bb);
     
          bb.putFloat(3.4f);
          printVars("bb.putFloat(3.4f)", bb);
     
          bb.flip();
          printVars("flip()", bb);
     
          bb.put((byte) 2);
          printVars("bb.put((byte) 2)", bb);
     
          bb.position(5);
          printVars("bb.position(5)", bb);
     
          bb.clear();
          printVars("clear()", bb);
       }
     
       public static void printVars(String state, ByteBuffer bb) {
          System.out.println(state);
          printTag("limit", bb.limit());
          printTag("position", bb.position());
          printLine(bb);
          System.out.print("t| ");
          for (int i=0; i<bb.capacity(); i++) {
             String hexValue = getHexValue(bb, i);
             System.out.print(" " + hexValue.toUpperCase() + " | ");
          }
          System.out.println();
          printLine(bb);
          System.out.println("tCapacity: " + bb.capacity() + 
                             ", remaining: " + bb.remaining());
          System.out.println();
       }
     
       public static void printLine(ByteBuffer bb) {
          System.out.print("t+");
          for (int i=0; i<bb.capacity(); i++) {
             System.out.print("-----+");
          }
          System.out.println();
       }
     
       public static void printTag(String tag, int pos) {
          System.out.print("t   ");
          for (int i=0; i<pos; i++) {
             System.out.print("      ");
          }
          System.out.println(tag);
          System.out.print("t   ");
          for (int i=0; i<pos; i++) {
             System.out.print("      ");
          }
          System.out.println("|");
       }
     
       public static String getHexValue(ByteBuffer bb, int pos) {
          String hexValue = "??";
          if (pos >= bb.limit()) {
             hexValue = "??";
          }
          else {
             hexValue = Integer.toHexString(bb.get(pos));
          }
          if (hexValue.length() > 2) {
             hexValue = hexValue.substring(hexValue.length()-2);
          }
          else if (hexValue.length() == 1) {
             hexValue = "0" + hexValue;
          }
          return hexValue;
       }
    }
    

    outputs:

    Initial state
    	                                                               limit
    	                                                               |
    	   position
    	   |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  00 |  00 |  00 |  00 |  00 |  00 |  00 |  00 |  00 |  00 | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 10
     
    bb.put((byte) 1)
    	                                                               limit
    	                                                               |
    	         position
    	         |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  01 |  00 |  00 |  00 |  00 |  00 |  00 |  00 |  00 |  00 | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 9
     
    bb.putFloat(3.4f)
    	                                                               limit
    	                                                               |
    	                                 position
    	                                 |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  01 |  40 |  59 |  99 |  9A |  00 |  00 |  00 |  00 |  00 | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 5
     
    flip()
    	                                 limit
    	                                 |
    	   position
    	   |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  01 |  40 |  59 |  99 |  9A |  ?? |  ?? |  ?? |  ?? |  ?? | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 5
     
    bb.put((byte) 2)
    	                                 limit
    	                                 |
    	         position
    	         |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  02 |  40 |  59 |  99 |  9A |  ?? |  ?? |  ?? |  ?? |  ?? | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 4
     
    bb.position(5)
    	                                 limit
    	                                 |
    	                                 position
    	                                 |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  02 |  40 |  59 |  99 |  9A |  ?? |  ?? |  ?? |  ?? |  ?? | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 0
     
    clear()
    	                                                               limit
    	                                                               |
    	   position
    	   |
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	|  02 |  40 |  59 |  99 |  9A |  00 |  00 |  00 |  00 |  00 | 
    	+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
    	Capacity: 10, remaining: 10