| 下面分析下Netty线程池NioEventLoopGroup的设计与实现细节,NioEventLoopGroup的类层次关系见图7: 图7 –NioEvenrLoopGroup类层次关系 其创建过程——方法调用,见下图: 图8 –NioEvenrLoopGroup创建调用关系 NioEvenrLoopGroup的创建,具体执行过程是执行类MultithreadEventExecutorGroup的构造方法: /**   * Create a new instance.   *   * @param nThreads          the number of threads that will be used by this instance.   * @param executor          the Executor to use, or {@code null} if the default should be used.   * @param chooserFactory    the {@link EventExecutorChooserFactory} to use.   * @param args              arguments which will passed to each {@link #newChild(Executor, Object...)} call   */  protected MultithreadEventExecutorGroup(int nThreads, Executor executor,                                          EventExecutorChooserFactory chooserFactory, Object... args) {      if (nThreads <= 0) {          throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));      }      if (executor == null) {          executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());      }      children = new EventExecutor[nThreads];      for (int i = 0; i < nThreads; i ++) {          boolean success = false;          try {              children[i] = newChild(executor, args);              success = true;          } catch (Exception e) {               throw new IllegalStateException("failed to create a child event loop", e);          } finally {              if (!success) {                  for (int j = 0; j < i; j ++) {                      children[j].shutdownGracefully();                  }                  for (int j = 0; j < i; j ++) {                      EventExecutor e = children[j];                      try {                          while (!e.isTerminated()) {                              e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);                          }                      } catch (InterruptedException interrupted) {                          // Let the caller handle the interruption.                          Thread.currentThread().interrupt();                          break;                      }                  }              }          }      }      chooser = chooserFactory.newChooser(children);      final FutureListener<Object> terminationListener = new FutureListener<Object>() {          @Override          public void operationComplete(Future<Object> future) throws Exception {              if (terminatedChildren.incrementAndGet() == children.length) {                  terminationFuture.setSuccess(null);              }          }      };      for (EventExecutor e: children) {          e.terminationFuture().addListener(terminationListener);      }      Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);      Collections.addAll(childrenSet, children);      readonlyChildren = Collections.unmodifiableSet(childrenSet);  } 
 (编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |