Search code examples
javasocketsnio

Java NIO socket IO degenerating read chunk size


I'm writing a non-blocking client that reads data from a network socket using selector SelectionKey.OP_READ and selector.select() calls. The reading part is handled like this:

if (selectionKey.isReadable()) {
    int len = inChannel.read(buf);
    System.out.println(len);
    . . .
}

The problem I see is that the read size (len) is gradually degenerating as the download progresses:

1290
1290
1290
480
318
28
28
28
28
28
28
28
28
28
28
28
28
28

Does anyone know why this is and how to improve it? Of course, it works as-is, but I need to reduce cpu overhead, and thus it is best to process large chunks instead of small ones. Adding a small sleep (20ms) helps, but will obviously limit scalability, as I need to handle thousands of streams simultaneously.


Solution

  • Going to answer my own question...

    Never mind; I wasn't using the buffer correctly. Forgot the compact() call after reading from buffer.

    if (selectionKey.isReadable()) {
        int len = inChannel.read(buf);
        System.out.println(len);
        . . .
        buf.flip();
        // ... read from buf ...
        buf.compact();
    }
    

    Apparently the buffers are not circular; even though a buffer is empty, the position and limit must be reset before next use.