Java Circular Byte Buffer that Extends java.nio.ByteBuffer

LINEMAN78 picture LINEMAN78 · Mar 4, 2011 · Viewed 7k times · Source

Every Java circular byte buffer implementation I have seen referenced on SO and elsewhere does not extend java.nio.ByteBuffer, which for me is necessary for use with a SocketChannel. Does anyone know of an open source implementation that extends ByteBuffer. I tried going down the road of writing my own, but got stuck when I realized that the position and remaining functions are final and I was going to override those to adjust for head and prevent buffer overflow exceptions. In sending 5000 messages over a socket channel with every one needing me to copy stuff to the head of a linear buffer this adds about 450ms or 90us per message(which contains 10 packets, so 9us per packet). Right now the only method that I can think of that would work is to override every single method and rewrite everything. Any ideas?

Answer

Peter Lawrey picture Peter Lawrey · Mar 4, 2011

Instead of creating a circular buffer you can make the buffer much larger than one message. Say the maximum message size is N bytes. Create a buffer which is 100 * N bytes are only compact() the ByteBuffer when there is less than N bytes left. This will reduce the amount of copying by a factor of 100.

Another optimisation is to compact() the ByteBuffer whenever there is no remaining data as this is very fast.