OP_READ
Operation-set bit for read operations.
Suppose that a selection key's interest set contains OP_READ at the start of a selection operation. If the selector detects that the corresponding channel is ready for reading, has reached end-of-stream, has been remotely shut down for further reading, or has an error pending, then it will add OP_READ to the key's ready-operation set and add the key to its selected-key set.
OP_WRITE
写就绪相对有一点特殊,一般来说,你不应该注册写事件。写操作的就绪条件为底层缓冲区有空闲空间,而写缓冲区绝大部分时间都是有空闲空间的,所以当你注册写事件后,写操作一直是就绪的,选择处理线程全占用整个CPU资源。所以,只有当你确实有数据要写时再注册写操作,并在写完以后马上取消注册。
当有数据在写时,将数据写到缓冲区中,并注册写事件。
public void write(byte[] data) throws IOException { writeBuffer.put(data); key.interestOps(SelectionKey.OP_WRITE); }
注册写事件后,写操作就绪,这时将之前写入缓冲区的数据写入通道,并取消注册。
channel.write(writeBuffer); key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
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.
只有数据可以写时才注册OP_WRITE操作。
避免死锁的一个简单方法就是不要在同一个socket同时注册多个操作。