SelectionKey with empty interest set

1.1k views Asked by At

I created an abstraction

public interface Channel<R extends SelectableChannel & ReadableByteChannel, W extends SelectableChannel & WritableByteChannel>

for java.nio.channels.SelectableChannel, it provides an isBidirectional method and getters to retrieve the write/read channel (which may or may not be equal). This channel and possibly multiple other instances of it are used with a dispatcher for i/o that encapsulates a selector.

Since I want to have non-blocking write, the dispatcher populates mutliple queues with ByteBuffers that should be written to the corresponding channels and adds java.nio.channels.SelectionKey.OP_WRITE to the key's interest set, if a write is due.

For bidirectional channels it's a simple update operation, since the read channel (== write channel), is already processed with interest OP_READ. If the channel is unidirectional, I have to get the write channel (!= read channel) and register it with interest OP_WRITE.


QUESTION

What should I do after I have performed my write operation assuming the queue is empty now? For bidirectional channels, I simply have to reset the interest set to OP_READ.

But how should I handle unidirectional channels, is it okay to invoke key.interestOps(0);, it does not violate the method's invariant

(ops & ~channel().validOps()) != 0.

The interest set of the (unidirectional) write channel would then be empty.


IN SHORT

Is java.nio.channels.SelectionKey.interestOps(0) a correct invocation, if I'm currently not interested in the selection key? Or should I remove the key?

2

There are 2 answers

2
user207421 On BEST ANSWER

Is it okay to invoke key.interestOps(0);

Yes, this is perfectly OK.

0
Rohan Emmanuel On

it means that you are not interest for any operation of that key, hence this will reset the earlier operations which were of interest.

by doing so, you are telling selector that for now ignore this key.