Networking applications always need ByteBuffer that can expand on the need basis. Java ByteBuffer doesn’t provide this feature. Fortunately, MINA’s IoBuffer class has implemented this much needed feature.
Creating Auto Expanding Buffer
IoBuffer class in MINA has a property autoExpand, which when set makes the IoBuffer expand on the need basis, very much similar to StringBuffer class.
Let’s see, how we can achieve this
IoBuffer buffer = IoBuffer.allocate(8); buffer.setAutoExpand(true); buffer.putString("12345678", encoder); // Add more to this buffer buffer.put((byte)10);
When we set this property, the buffer will expand as and when needed. Under the hood, it essentially allocated a new IoBuffer and returns the new instance with the copied data.
So, can we shrink the buffer as well. Yes, if we set the autoshrink property to true.
IoBuffer buffer = IoBuffer.allocate(8); buffer.setAutoShrink(true); buffer.put((byte)7); System.out.println("Buffer size = "+buffer.capacity()); buffer.shrink(); buffer.capacity(16); System.out.println("Buffer size = "+buffer.capacity()); buffer.shrink(); System.out.println("Buffer size = "+buffer.capacity());
Here we set autoShrink property to true. To manually shrink the capacity, we use shrink() method. Caution, shrink(), won’t reduce capacity below the minimum capacity (the capacity with which the buffer was created). The second call to shrink(), will reduce the capacity to 8.
Has updated the MINA’s documentation page on IoBuffer today. So please feel free to find more details here