javareal-timecss-selectorsniobytebuffer

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


Can someone with the natural gift to explain complex things in an easy and straightforward way address this question? To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO?


For example: Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer?


Solution

  • To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO?

    Direct buffers have a number of advantages

    Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer?

    If you are reading a byte at a time, you may not get much advantage. However, with a direct byte buffer you can read 2 or 4 bytes at a time and effectively parse multiple bytes at once.

    [real time] [selectors]

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

    EDIT: Here is a high performance library that is relatively easy to use that uses blocking NIO you can draw on https://github.com/OpenHFT/Chronicle-Wire/tree/ea/src/main/java/net/openhft/chronicle/wire/channel