分享内容如下
- IO事件执行
- processSelectedKeysOptimized分析
- needsToSelectAgain分析
- processSelectedKey分析
- NioEventLoop父子类分析
- IO任务和定时任务
IO事件执行
processSelectedKeysOptimized分析
private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) {
for (int i = 0;; i ++) {
final SelectionKey k = selectedKeys[i];
if (k == null) {
break;
}
final Object a = k.attachment();
if (a instanceof AbstractNioChannel) {//普通IO事件
processSelectedKey(k, (AbstractNioChannel) a);
} else {//执行NioTask
@SuppressWarnings("unchecked")
NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
processSelectedKey(k, task);
}
if (needsToSelectAgain) {
selectAgain();
// Need to flip the optimized selectedKeys to get the right reference to the array
// and reset the index to -1 which will then set to 0 on the for loop
// to start over again.
//
// See https://github.com/netty/netty/issues/1523
selectedKeys = this.selectedKeys.flip();
i = -1;
}
}
}
NioTask接口用于自定义 channel已经准备好 和channel关闭处理逻辑, 只在netty 源码的测试类中找到
关联了SelectionKey.OP_CONNECT。
needsToSelectAgain分析
这个值默认为false,在 NioEventLoop-cancel()中修改为false
void cancel(SelectionKey key) {
key.cancel();
cancelledKeys ++;
if (cancelledKeys >= CLEANUP_INTERVAL) {//CLEANUP_INTERVAL默认为256 不可以配置
cancelledKeys = 0;
needsToSelectAgain = true;
}
}
看一下cannel什么时候被调用
分析得知 当底层IO处理,如connect,register,bind,read 发生异常都会触发cannel方法。
needsToSelectAgain 在processSelectedKeysOptimized执行过程中 执行了256次cancel,则执行</