NIO write taking up all the process resources

How should the writing to a non-blocking nio channel be handled?


if (key.isAcceptable()) {
~ codes ~
client.register(selector, SelectionKey.OP_READ |  SelectionKey.OP_WRITE);
}  else if (key.isConnectable()) {
~ codes ~
client.register(selector, SelectionKey.OP_READ |  SelectionKey.OP_WRITE);
} else if (key.isReadable()) {
~ codes ~
} else if (key.isWritable()) {
~ codes ~
<== writes data to the channel here ==>
}

Apperently if I use that the select will keep returning, therefore eating up the resources.
According to this page http://www-128.ibm.com/developerworks/java/library/j-perf03174.html, [quote]if the socket is registered with the Selector in WRITE mode, then the Selector.select() call will always return immediately, because it has at least one socket which is ready to be written to.
[/quote]
Now my problem, since calling register() function in a thread other than the one that calls select() will cause blocking problem. How would I write data to the channel if I can’t register the channel to write state?

I had the same problem and I figured it out in 10 mins what was happening, unlike the guy from link you gave (he must have written it all and then started testing couse he couldn’t have missed it the otherway). You don’t have to read it since I’ll tell you anyway, but let it be official:
http://www.java-gaming.org/forums/index.php?topic=12768.0

Anyway when you register for OP_WRITE it will return from select() almost all the time since network card is almost never full with data. So you actually need to register OP_WRITE before the write itself and unregister after the write. This “problem” and solution is well explained in the link you gave so it’s obvious that you didn’t even bother to read it until the end.