bennyl bennyl - 1 month ago 10
Java Question

Java: SelectionKey.interestOps(int) not thread safe?

In my application I use multiple threads to handle client connections.

i found a very weird behavior when debugging - I have a SelectionKey that by invoking (using the debugger) its interestOps() method the return value is 1 (READ), but when I send data to the socket corresponding to that key the selector not wakes up..

If using the debugger I changes the specific selection key interest ops to 1 (even though it was 1) the selector suddenly react to that change.

I have only one thread handling a connection at a given time but this thread is not specific to that connection, if I disable the multi-threading (set the thread pool to be of size 1) this problem never occurred.

By looking at the SelectionKey class documentation - this method should be thread safe - did i miss something?

Answer

The problem was solved after i moved all the changes to the interestOps to be done on the selector thread - so I guess that interestOps(int) is not thread safe.

Edit
by moving all the interestOps changes to the selector thread I also gain 30% speedup - not sure why but this is the only change between my tests..