A simple rule, when should I use direct buffers with Java NIO for network I / O?

Can someone with a natural gift easily and simply explain complex things in a simple and understandable way? To get maximum performance, when should I use direct ByteBuffers and regular ByteBuffers when performing network I / O with Java NIO?


For example: Do I have to read the heap buffer and parse it there by doing a lot of get () (byte by byte) OR should I read it in a direct buffer and parse from a direct buffer?

+9
java css-selectors nio real-time bytebuffer
source share
2 answers

To get maximum performance, when should I use direct ByteBuffers and regular ByteBuffers when performing network I / O with Java NIO?

Direct buffers have several advantages.

  • To avoid an extra copy of the data transferred between Java and its own memory.
  • If they are reused, only the used page turns into real memory. This means that you can make them much larger than I need, and they only spend virtual memory.
  • You can access multibyte primitives in your own byte order. (Basically one machine code instruction)

Do I have to read heaps in the buffer and parse it there by doing a lot of get () (byte by byte) OR should I read it into a direct buffer and parse from a direct buffer?

If you read bytes at a time, you cannot get many advantages. However, using a direct byte buffer, you can read 2 or 4 bytes at a time and efficiently analyze several bytes at once.

[real time] [selectors]

If you are analyzing data in real time, I would avoid using selectors. I found that using NIO locks or waiting for NIO can give you the lowest latency performance (assuming you have a relatively small number of connections, e.g. up to 20)

+11
source share

A direct buffer is best when you simply copy data from, say, a socket to a file or vice versa, since the data should not cross the JNI / Java border, it just stays on the JNI ground. If you plan to independently view the data, there is no point in the direct buffer.

+4
source share

All Articles