Java Circular Byte Buffer extending java.nio.ByteBuffer

Each Java buffer byte byte implementation that I have seen on SO and elsewhere does not extend the java.nio.ByteBuffer, which is necessary for me to use with SocketChannel. Does anyone know of an open source implementation that extends ByteBuffer. I tried to go down the road to write my own, but got stuck when I realized that the position and the remaining functions are final, and I was going to redefine them to adjust my head and prevent buffer overflow exceptions. When sending 5,000 messages over a socket channel to anyone I need to copy material to the head of a linear buffer, this adds about 450 ms or 90 ounces per message (which contains 10 packets, which means 9us per packet). Right now, the only way I can think that this will work is to override each method and rewrite everything. Any ideas?

+8
java buffer bytebuffer
source share
4 answers

Instead of creating a circular buffer, you can make the buffer much larger than a single message. Say the maximum message size is N bytes. Creating a buffer that is 100 * N bytes is only compact () ByteBuffer when less than N bytes are left. This will reduce the number of copies by 100 times.

Another optimization is the compact () ByteBuffer whenever there is no remaining data, as it is very fast.

+6
source share

You cannot extend java.nio.ByteBuffer , simply. C-tor is a private package. This will NOT work, b / c. The basic idea is to pass the address to some C code. Also, you cannot override anything, since many of these methods are final. ByteBuffers were designed for speed, and some of the solutions may look weird, but they are fine.

java.nio.channels.GatheringByteChannel and java.nio.channels.ScatteringByteChannel worth a try, although there are quite a few implementation-dependent (native C) ones to ensure their usefulness.

+5
source share
+1
source share

I would use the ByteBuffer.wrap () method. By taking a close look at the Cisco implementation that Mr. Dean Hiller published earlier, you can replace put () with getWriteBuffer (), which will return you a ByteBuffer, which wraps the part in a buffer that it can write.

The same logic can be applied to the reading part.

The advantage would be that it would not have compactness, which could be expensive depending on the number of bytes available in the ByteBuffer, by bundling the parsing logic: you can get the first part of your message for ByteBuffer, wraps the last area of ​​the lying at the core of the circular buffer. To get the second part of your message, another reading is required to get an array of bytes at the beginning of the circular buffer wrapped in another ByteBuffer.

0
source share

All Articles