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
1 2 3 4 5 6 |
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.
1 2 3 4 5 6 7 8 9 |
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
Hello, I’ve enjoyed reading your blog. While reading your example about expanding buffers. I questioned my self how can I read out the 2 values: buffer.putString(“12345678”, encoder); buffer.put((byte)10);
I tried it the following way:
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putInt(1);
buffer.putString(“xxx”,encoder );
System.out.println(buffer.getInt(0)+”: “);
System.out.println(buffer.getString(decoder);
This doesn’t produce the right outcome. It only shows the int. In the MINA docs I didn’t find anything to help me.
Thanks