0

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.

1
  • I think you should reconsider what you are trying to do. A non-blocking read means "give me the data you have right now, and return ASAP". A non-blocking read which waited to get more data would actually be a blocking read, wouldn't it? What should the process do while it's waiting for data?
    – Flavio
    Jul 11, 2012 at 8:46

1 Answer 1

0

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.

1
  • You must flip() the buffer before getting anything out of it, and compact() it afterwards.
    – user207421
    Jul 11, 2012 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.