Search code examples
javanio

java NIO, selectedKeys, and channels for STDIN, STDOUT, STDERR


I have a program that pipes stdout, stderr, and stdin through Pipe.SourceChannel's to/from BytesBuffers.

The program registers each channel with a selector.

The program in a loop periodically iterates through each key in the set of selectedKeys, which correspond to stdout, stderr, and stdin. For each key, it determines if the key is valid, and readable or writable, and if so, it conducts the corresponding IO operation to/from a ByteBuffer

My question is what can I assume about the set of initially selected keys (corresponding to stdin , stdout , stderr) when the program begins.

Will the key for stdin be always be the first key to be ready, valid and readable? Could the key for stdout be ready, valid and readable before stdin?

I ask because my programs behavior is having random IO behavior, and I'm guessing that my assumptions about initial key set membership are wrong.

Thanks in advance.


Solution

  • Channels are readable when there is data that can be read without blocking.

    Channels are writable except when there is no room in their kernel socket send buffers, which only happens if they are writing faster than the reader is reading.