handler 执行中如何换人?

关键代码 io.netty.channel.AbstractChannelHandlerContext#invokeChannelRead()

  1. static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
  2. final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
  3. // 下一个 handler 的事件循环是否与当前的事件循环是同一个线程
  4. EventExecutor executor = next.executor();
  5. // 是,直接调用
  6. if (executor.inEventLoop()) {
  7. next.invokeChannelRead(m);
  8. }
  9. // 不是,将要执行的代码作为任务提交给下一个事件循环处理(换人)
  10. else {
  11. executor.execute(new Runnable() {
  12. @Override
  13. public void run() {
  14. next.invokeChannelRead(m);
  15. }
  16. });
  17. }
  18. }
  • 如果两个 handler 绑定的是同一个线程,那么就直接调用
  • 否则,把要调用的代码封装为一个任务对象,由下一个 handler 的线程来调用