When using Java NIO, I got some problems.
I need to change the interestOps
of a key
. I found here are two ways to do it.
First is done by invoking key.interestOps()
:
key.interestOps(OP_READ)
However I encountered with very tricky thread-safe issues in this way:
key.interestOps(OP_WRITE);
sl.select();
Iterator iter = sl.selectedKeys().iterator();
log(iter.toArray().length); // Sometimes, I got 0 here!
The interesting thing is I got 0 sometimes in log (But sometimes it just works well). But there is no explicit modification of key in other threads. I can't understand what happened between the line2
and line3
.
Another way is to register
again:
The problem is the new return key
lost his buffer:
key = sockChannel.register(selector, OP_WRITE);
key.attach(buf);
sockChannel.register(selector, OP_READ);
key.attachment();// nullExcetion here!
Of course this can be fixed by reassigning the buffer, but I'm sure things can be better.
Any insights?