Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Circular Byte Buffer that Extends java.nio.ByteBuffer

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?

like image 789
LINEMAN78 Avatar asked Mar 04 '11 00:03

LINEMAN78


3 Answers

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.

like image 130
Peter Lawrey Avatar answered Oct 06 '22 22:10

Peter Lawrey


You cannot extend java.nio.ByteBuffer, simple as that. The c-tor is package private. It will NOT work, b/c the main idea is passing the address to some C code. Also you cannot override anything since many of the methods are final. ByteBuffers have been engineered for speed and some of the decisions may look weird but they are ok.

java.nio.channels.GatheringByteChannel and java.nio.channels.ScatteringByteChannel worth a try, although there are quite a bit implementation dependent (native C) to make them useful.

like image 29
3 revs Avatar answered Oct 06 '22 23:10

3 revs


We might try this one since it is apache license

https://svn.apache.org/repos/asf/etch/releases/release-1.0.0/util/src/main/java/etch/util/CircularByteBuffer.java

like image 2
Dean Hiller Avatar answered Oct 06 '22 23:10

Dean Hiller