总览


EventLoopGroup到底是什么?

EventLoopGroup是一个存储EventLoop的容器,同时他应该具备线程池的功能。

 
 
EventLoopGroup
EventExecutorGroup
ScheduledExecutorService

由于EventLoopGroup间接继承ScheduledExecutorService接口,因此其实现类应该具备线程池的功能。

看一下NioEventLoopGroup的核心属性

    // 默认的线程池大小     private static final int DEFAULT_EVENT_LOOP_THREADS;      static {         DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(                 "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); // CPU核数 x 2     }          // 存储EventLoop的数组     private final EventExecutor[] children; 

构造方法

    // 如果传入的nThread为空,那么使用默认的线程池大小(CPU核数 x 2)     protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) {         super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args);     }      // 最终的构建方法     protected MultithreadEventExecutorGroup(int nThreads, Executor executor,                                             EventExecutorChooserFactory chooserFactory, Object... args) {         // ......省略          children = new EventExecutor[nThreads]; // 初始化EventExecutor数组的大小          for (int i = 0; i < nThreads; i ++) {             boolean success = false;             try {                 children[i] = newChild(executor, args); // 初始化EventLoop                 success = true;             } catch (Exception e) {                 throw new IllegalStateException("failed to create a child event loop", e);             } finally {                 // ......省略             }         }         // ......省略     } 

当创建NioEventLoopGroup实例后,就已经初始化好其EventExecutor数组的大小以及其存储的EventLoop。