zoukankan      html  css  js  c++  java
  • netty的线程池-----揭示了使用两个线程池的原因

    线程模型是Netty的核心设计,设计地很巧妙,之前项目中有一块处理并发的设计和Netty的Eventloop单线程设计类似,效果得到了实证。

    Netty5的类层次结构和之前的版本变化很大,网上也有很多文章写Netty的线程模型,Reactor模式,比如这篇http://blog.csdn.net/xiaolang85/article/details/37873059, 应该是引自《Netty权威指南》,写得比较全面,但是有几个关键的概念没讲清楚。

    这篇文章只讲Netty5线程模型最重要的几个关键点

    第一个概念是如何理解NioEventLoop和NioEventLoopGroup:NioEventLoop实际上就是工作线程,可以直接理解为一个线程。NioEventLoopGroup是一个线程池,线程池中的线程就是NioEventLoop。Netty设计这几个类的时候,层次结构挺复杂,反而让人迷惑。

    还有一个让人迷惑的地方是,创建ServerBootstrap时,要传递两个NioEventLoopGroup线程池,一个叫bossGroup,一个叫workGroup。《Netty权威指南》里只说了bossGroup是用来处理TCP连接请求的,workGroup是来处理IO事件的。

    这么说是没错,但是没说清楚bossGroup具体如何处理TCP请求的。实际上bossGroup中有多个NioEventLoop线程,每个NioEventLoop绑定一个端口,也就是说,如果程序只需要监听1个端口的话,bossGroup里面只需要有一个NioEventLoop线程就行了。

    在上一篇文章介绍服务器端绑定的过程中,我们看到最后是NioServerSocketChannel封装的Java的ServerSocketChannel执行了绑定,并且执行accept()方法来创建客户端SocketChannel的连接。一个端口只需要一个NioServerSocketChannel即可。

    [java] view plaincopy
     
     
     
    1.                 EventLoopGroup bossGroup = new NioEventLoopGroup();  
    2.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
    3.         try {  
    4.             ServerBootstrap b = new ServerBootstrap();  
    5.             b.group(bossGroup, workerGroup)  
    6.                     .channel(NioServerSocketChannel.class)  
    7.                     .option(ChannelOption.SO_BACKLOG, 1024)  
    8.                     .childHandler(new ChildChannelHandler());  
    9.               
    10.             ChannelFuture f = b.bind(port).sync();  
    11.             f.channel().closeFuture().sync();  
    12.         } finally {  
    13.             bossGroup.shutdownGracefully();  
    14.             workerGroup.shutdownGracefully();  
    15.         }  
    16.   
    17.   
    18.     protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {  
    19.         if (nThreads <= 0) {  
    20.             throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));  
    21.         }  
    22.   
    23.         if (executor == null) {  
    24.             executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());  
    25.         }  
    26.   
    27.         children = new EventExecutor[nThreads];  
    28.         for (int i = 0; i < nThreads; i ++) {  
    29.             boolean success = false;  
    30.             try {  
    31.                 children[i] = newChild(executor, args);  
    32.                 success = true;  
    33.             } catch (Exception e) {  
    34.                 // TODO: Think about if this is a good exception type  
    35.                 throw new IllegalStateException("failed to create a child event loop", e);  
    36.             } finally {  

    第二个概念是每个NioEventLoop都绑定了一个Selector,所以在Netty5的线程模型中,是由多个Selecotr在监听IO就绪事件。而Channel注册到Selector。

    举个例子,比如有100万个连接连到服务器端。平时的写法可能是1个Selector线程监听所有的IO就绪事件,1个Selector面对100万个连接(Channel)。

    而如果使用了1000个NioEventLoop的线程池来说,1000个Selector面对100万个连接,每个Selector只需要关注1000个连接(Channel)

    [java] view plaincopy
     
     
     
    1. public final class NioEventLoop extends SingleThreadEventLoop {  
    2.   
    3.     
    4.     /** 
    5.      * The NIO {@link Selector}. 
    6.      */  
    7.     Selector selector;  
    8.     private SelectedSelectionKeySet selectedKeys;  
    9.   
    10.     private final SelectorProvider provider;  



    第三个概念是一个Channel绑定一个NioEventLoop,相当于一个连接绑定一个线程,这个连接所有的ChannelHandler都是在一个线程中执行的,避免的多线程干扰。更重要的是ChannelPipline链表必须严格按照顺序执行的。单线程的设计能够保证ChannelHandler的顺序执行。

    [java] view plaincopy
     
     
     
    1. public interface Channel extends AttributeMap, Comparable<Channel> {  
    2.   
    3.     /** 
    4.      * Return the {@link EventLoop} this {@link Channel} was registered too. 
    5.      */  
    6.     EventLoop eventLoop();  

    第四个概念是一个NioEventLoop的selector可以被多个Channel注册,也就是说多个Channel共享一个EventLoop。EventLoop的Selecctor对这些Channel进行检查。

    这段代码展示了线程池如何给Channel分配EventLoop,是根据Channel个数取模

    [java] view plaincopy
     
     
     
    1.  public EventExecutor next() {  
    2.         return children[Math.abs(childIndex.getAndIncrement() % children.length)];  
    3.     }  
    4.   
    5. private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) {  
    6.         for (int i = 0;; i ++) {  
    7.             // 逐个处理注册的Channel  
    8.             final SelectionKey k = selectedKeys[i];  
    9.             if (k == null) {  
    10.                 break;  
    11.             }  
    12.   
    13.             final Object a = k.attachment();  
    14.   
    15.             if (a instanceof AbstractNioChannel) {  
    16.                 processSelectedKey(k, (AbstractNioChannel) a);  
    17.             } else {  
    18.                 @SuppressWarnings("unchecked")  
    19.                 NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;  
    20.                 processSelectedKey(k, task);  
    21.             }  
    22.   
    23.             if (needsToSelectAgain) {  
    24.                 selectAgain();  
    25.                 // Need to flip the optimized selectedKeys to get the right reference to the array  
    26.                 // and reset the index to -1 which will then set to 0 on the for loop  
    27.                 // to start over again.  
    28.                 //  
    29.                 // See https://github.com/netty/netty/issues/1523  
    30.                 selectedKeys = this.selectedKeys.flip();  
    31.                 i = -1;  
    32.             }  
    33.         }  
    34.     }  



    理解了这4个概念之后就对Netty5的线程模型有了清楚的认识:

    在监听一个端口的情况下,一个NioEventLoop通过一个NioServerSocketChannel监听端口,处理TCP连接。后端多个工作线程NioEventLoop处理IO事件。每个Channel绑定一个NioEventLoop线程,1个NioEventLoop线程关联一个selector来为多个注册到它的Channel监听IO就绪事件。NioEventLoop是单线程执行,保证Channel的pipline在单线程中执行,保证了ChannelHandler的执行顺序。

    下面这张图来之http://blog.csdn.net/xiaolang85/article/details/37873059, 基本能说清楚。

  • 相关阅读:
    常用设计模式:装饰者模式
    常用数据结构算法 : 堆排序
    常用数据结构算法:二叉树的最近公共祖先
    java网络通信:HTTP协议 之 Sessions与Cookies
    java网络通信:HTTP协议
    常见的设计模式:工厂模式
    Java基础:类加载机制
    一个C++右值引用的问题
    剖析一个用C++写的行情交易系统
    C++ Coroutine简明教程
  • 原文地址:https://www.cnblogs.com/tiancai/p/9959572.html
Copyright © 2011-2022 走看看