Netty源码分析:1.1初始化NioEventLoopGroup

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GG_and_DD/article/details/80416885

第一章节是主要是服务器启动的代码分析。章节目录有:
|———1.1初始化NioEventLoopGroup
|———1.2初始化NioEventLoop
|———1.3初始化NioServerSocketChannel
|———1.4服务器启动流程
为什么先从初始化开始了解服务器启动?
因为在我看服务器启动的相关源码的时候,有很多地方都是初始化的时候已经建立好的。所以我就从初始化的源码开始看起。这是我第一次看源码的笔记,仍有很多理解错误的地方和不解的地方。欢迎讨论。

本篇目录:

  • 继承关系类图
  • 初始化时序图
  • NioEventLoopGroup源码分析
  • 总结

继承关系类图

image.png

初始化时序图

image.png

代码debug开始于new NioEventLoopGroup();

1. NioEventLoopGroup默认有参构造

虽然我们在new NioEventLoopGroup()的时候并没有传入参数,但是在初始化的时候,NioEventLoopGroup 类会自动调用自己的有参构造函数,并且调用父类的有参构造进行初始化。
- 第一个参数int nThreads: 建立多少个线程数,如果传入是0.则默认是cpu*2的个数。
- 第二个参数Executor executor: 初始化是null。
- 第三个参数SelectorProvider selectorProvider:是一个SelectorProvider.provider()的返回值。
- 第四个参数RejectedExecutionHandler的返回值:是一个处理异常的类

SelectorProvider就是为了创建DatagramChannel,Pipe,Selector,ServerSocketChannel,SocketChannel,System.inheritedChannel()而服务的

public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }

2. MultithreadEventLoopGroup

接下来是父类的初始化.在这一步可以看到是继续调用super()进行一个父类的有参构造。 在这里可以看到nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads .也就是说如果new NioEventLoopGroup() 的时候没有定义nThreads那么默认值是0,如果是0,则传入的数是DEFAULT_EVENT_LOOP_THREADS(cpu*2的线程数。)

 protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
        super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
    }

3. MultithreadEventExecutorGroup

在这里 MultithreadEventExecutorGroup 再一次调用自己有参构造,并传入一个参数,DefaultEventExecutorChooserFactory.INSTANCE,其实是返回一个DefaultEventExecutorChooserFactory对象。该对象的作用就是获取EventExecutor对象的。

DefaultEventExecutorChooserFactory的内部原理就是:调用newChooser(EventExecutor[] e)方法,传入EventExecutor数组,返回一个PowerOfTwoEventExecutorChooser对象,该对象作用就是调用next()方法获取一个EventExecutor对象。所以说DefaultEventExecutorChooserFactory类就是获取EventExecutor对象的。

protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {
        this(nThreads, executor, DefaultEventExecutorChooserFactory.INSTANCE, args);
    }

接着是调用MultithreadEventExecutorGroup 另一个有参构造。
- 1 判断executor 是否为空,为空就创建一个ThreadPerTaskExecutor对象。
ThreadPerTaskExecutor
实现executor接口。
- 2 创建一个EventExecutor数组个数为nThreads个
- 3 初始化EventExecutor数组。调用的是newChild方法.下面分析一下newChild方法.步骤是:创建一个NioEventLoop线程,如果创建不成功
- 4 finally 是判断是否创建NioEventLoop对象成功。如果失败,就关闭线程。
- 5 在初始化第3步提到,就是用DefaultEventExecutorChooserFactory对象 管理一个EventExecutor数组。
- 6 创建一个监听器,当操作完成的时候,设置一个成功的信息。
- 7 给每一个EventExecutor添加一个监听器
- 8 创建一个set 存放这个EventExecutor数组。并赋予readonlyChildren变量

到此,初始化就已经完成了。

 protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
                                            EventExecutorChooserFactory chooserFactory, Object... args) {

        //检验参数
        if (nThreads <= 0) {
            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
        }

        //1
        if (executor == null) {
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }


        //2  
        children = new EventExecutor[nThreads];

        //3
        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 {
               //4
                        }
                    }
                }
            }
        }

        //5
        chooser = chooserFactory.newChooser(children);

        //6
        final FutureListener<Object> terminationListener = new FutureListener<Object>() {
            @Override
            public void operationComplete(Future<Object> future) throws Exception {
                if (terminatedChildren.incrementAndGet() == children.length) {
                    terminationFuture.setSuccess(null);
                }
            }
        };

        //7
        for (EventExecutor e: children) {
            e.terminationFuture().addListener(terminationListener);
        }
        //8
        Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
        Collections.addAll(childrenSet, children);
        readonlyChildren = Collections.unmodifiableSet(childrenSet);
    }

分析newChild()

在这里NioEventLoopGroup重写了父类MultithreadEventExecutorGroup的newChild()方法
可以看出是建立一个NioEventLoop的对象。

@Override
    protected EventLoop newChild(Executor executor, Object... args) throws Exception {
        return new NioEventLoop(this, executor, (SelectorProvider) args[0],
            ((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
    }

总结

我觉得NioEventLoopGroup的初始化就是,建立默认cup核数*2个的NioEventLoop。当有一个channel新连接的时候,将该channel与一个NioEventLoop绑定,该channel的任务全部交给NioEventLoop执行了。

猜你喜欢

转载自blog.csdn.net/GG_and_DD/article/details/80416885