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