參見
The Rox Java NIO Tutorial
一些principles
1.Use a single selecting thread
雖然selector本身是線程安全的,但是key集合卻不是線程安全的,使用多線程容易導致死鎖。
2.Use a single selecting thread
NIO底層實現在不同的平臺上是不一樣的,如果你編寫的程序可能要在不同的平臺上運行,那么必須遵循這一原則。
更改行為包括:修改一個select key感興趣的ops,向這個selector注冊新的channel或者從這個selector取消一個channel等。
3.Set OP_WRITE only when you have data ready
A common mistake is to enable OP_WRITE on a selection key and leave it set. This results in the selecting thread spinning because 99% of the time a socket channel is ready for writing. In fact the only times it's not going to be ready for writing is during connection establishment or if the local OS socket buffer is full. The correct way to do this is to enable OP_WRITE only when you have data ready to be written on that socket channel. And don't forget to do it from within the selecting thread.
4.Alternate between OP_READ and OP_WRITE