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

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.

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.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

Leave a 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.