Using Auto expanding and shrinking IoBuffer in Apache MINA

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.putString("12345678", encoder);
// Add more to this buffer

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);
System.out.println("Buffer size = "+buffer.capacity());
System.out.println("Buffer size = "+buffer.capacity());
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

One thought on “Using Auto expanding and shrinking IoBuffer in Apache MINA

  1. 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.putString(“xxx”,encoder );

    System.out.println(buffer.getInt(0)+”: “);

    This doesn’t produce the right outcome. It only shows the int. In the MINA docs I didn’t find anything to help me.


Leave a Reply to Thomas Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.