百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

Netty源码分析(一)——线程组初始化

liebian365 2024-10-15 13:52 33 浏览 0 评论

继上篇文章讲述了Netty的基本使用之后,下面从源码角度分析Netty的执行流程过程中做了哪些事情。

我们知道,Netty底层是对JDK的NIO进行封装,并且其架构基础是基于主从Reactor模型设计的,主线程组负责处理Accept连接,从线程组负责处理IO事件,由于Netty处理IO的事件都是异步的,无法立即得到返回结果,它需要对事件添加监听器,当事件处理完毕时,调用isSuccess()来判断结果是否成功,或者调用sync()方法来使异步变为同步。

由于Netty底层流程涉及非常多的复杂流程,这篇文章就从Netty的启动入口——事件循环组的初始化来分析。

下面这段代码,定义两个事件循环组,分别为bossGroup(它用来接收Accept请求)和workerGroup(处理IO事件)。

// bossGroup处理客户端连接,绑定线程数1
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// 处理IO事件的事件循环组,线程数为cpu的核心数*2
EventLoopGroup workerGroup = new NioEventLoopGroup();

NioEventLoopGroup继承关系:

NioEventLoop继承关系:

一个NioEventLoopGroup里面维护多个NioEventLoop,而每个NioEventLoop里面维护一个线程,事件的IO都是NioEventLoop里面对应的线程来执行的。

下面从源码方向分析:

初始化NioEventLoopGroup类:

public class NioEventLoopGroup extends MultithreadEventLoopGroup {
    // 无参构造方法
    public NioEventLoopGroup() {
        this(0);
    }
    
    // 指定线程数量的构造方法
    public NioEventLoopGroup(int nThreads) {
        this(nThreads, (Executor) null);
    }
    // 指定线程数量和执行器的构造方法
    public NioEventLoopGroup(int nThreads, Executor executor) {
        // SelectorProvider.provider()根据系统选择适配的选择器提供者
        this(nThreads, executor, SelectorProvider.provider());
    }
    
    //指定线程数量、执行器、Selector的构造方法
    public NioEventLoopGroup(
            int nThreads, Executor executor, final SelectorProvider selectorProvider) {
        this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }
    
    //指定线程数量、执行器、Selector、SelectStrategyFactory的构造方法
    public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        // 调用父类MultithreadEventLoopGroup的构造方法
        super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }
}

===》父类MultithreadEventLoopGroup的构造方法

public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup {
    private static final int DEFAULT_EVENT_LOOP_THREADS;

    static {
        // 线程数 = CPU的核数*2
        DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

        if (logger.isDebugEnabled()) {
            logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
        }
    }
    
    protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
        // 如果初始化的时候没有赋值线程数,将会使用系统默认的线程数=CPU的核数*2
        // 然后调用父类MultithreadEventExecutorGroup的构造方法
        super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
    }
}

===》父类MultithreadEventExecutorGroup的构造方法

public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {
    private final EventExecutor[] children;
    
    protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {
        this(nThreads, executor, DefaultEventExecutorChooserFactory.INSTANCE, args);
    }
    
    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) {
            // 使用默认的ThreadPerTaskExecutor线程执行,它实现JDK Executor接口,是一个管理线程池的工具类
            // 它跟Executor一样,只不过自己定义了线程工厂
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }

        // 初始化EventExecutor数组
        children = new EventExecutor[nThreads];

        for (int i = 0; i < nThreads; i ++) {
            boolean success = false;
            try {
                // 初始化EventExecutor对象,args表示多个参数
                children[i] = newChild(executor, args);
                success = true;
            } catch (Exception e) {
                // TODO: Think about if this is a good exception type
                throw new IllegalStateException("failed to create a child event loop", e);
            } finally {
                if (!success) {
                    // 如果初始化EventExecutor对象失败,则关闭所有已经创建的EventExecutor对象
                    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;
                        }
                    }
                }
            }
        }
        // 选择轮询执行器,这里面有两层判断:
        //(1)如果传进来的数是2的幂次方,则new PowerOfTwoEventExecutorChooser(executors)
        // (2) 如果不是,则是new GenericEventExecutorChooser(executors)
        // 最终,归根结底,都是实现轮询线程的效果
        chooser = chooserFactory.newChooser(children);

        //监听每个EventExecutor的关闭状态,所有EventExecutor都关闭了,Group也就关闭了
        final FutureListener<Object> terminationListener = new FutureListener<Object>() {
            @Override
            public void operationComplete(Future<Object> future) throws Exception {
                if (terminatedChildren.incrementAndGet() == children.length) {
                    terminationFuture.setSuccess(null);
                }
            }
        };

        // 给每个EventExecutor添加关闭状态监听器
        for (EventExecutor e: children) {
            e.terminationFuture().addListener(terminationListener);
        }

        Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
        Collections.addAll(childrenSet, children);
        // 创建一个只读的集合
        readonlyChildren = Collections.unmodifiableSet(childrenSet);
    }
}

关键的核心:children[i] = newChild(executor, args); 它是给EventExecutor数组里面赋值每个NioEventLoop,且每个NioEventLoop关联一个SingleThreadEventExecutor

public class NioEventLoopGroup{
		@Override
    protected EventLoop newChild(Executor executor, Object... args) throws Exception {
        EventLoopTaskQueueFactory queueFactory = args.length == 4 ? (EventLoopTaskQueueFactory) args[3] : null;
        return new NioEventLoop(this, executor, (SelectorProvider) args[0],
            ((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2], queueFactory);
    }
}

至此,线程池组就初始化完毕。

NioEventLoopNioEventLoopGroup的区别

  1. NioEventLoopGroupNioEventLoop的容器,提供了生成NioEventLoop的方法
  2. NioEventLoop负责IO的读写之外,还兼顾处理以下两类任务:系统Task、定时任务

后续文章:ServerBootstrap的加载过程源码分析

相关推荐

“版本末期”了?下周平衡补丁!国服最强5套牌!上分首选

明天,酒馆战棋就将迎来大更新,也聊了很多天战棋相关的内容了,趁此机会,给兄弟们穿插一篇构筑模式的卡组推荐!老规矩,我们先来看10职业胜率。目前10职业胜率排名与一周前基本类似,没有太多的变化。平衡补丁...

VS2017 C++ 程序报错“error C2065:“M_PI”: 未声明的标识符&quot;

首先,程序中头文件的选择,要选择头文件,在文件中是没有对M_PI的定义的。选择:项目——>”XXX属性"——>配置属性——>C/C++——>预处理器——>预处理器定义,...

东营交警实名曝光一批酒驾人员名单 88人受处罚

齐鲁网·闪电新闻5月24日讯酒后驾驶是对自己和他人生命安全极不负责的行为,为守护大家的平安出行路,东营交警一直将酒驾作为重点打击对象。5月23日,东营交警公布最新一批饮酒、醉酒名单。对以下驾驶人醉酒...

Qt界面——搭配QCustomPlot(qt platform)

这是我第一个使用QCustomPlot控件的上位机,通过串口精确的5ms发送一次数据,再将读取的数据绘制到图表中。界面方面,尝试卡片式设计,外加QSS简单的配了个色。QCustomPlot官网:Qt...

大话西游2分享赢取种族坐骑手办!PK趣闻录由你书写

老友相聚,仗剑江湖!《大话西游2》2021全民PK季4月激燃打响,各PK玩法鏖战齐开,零门槛参与热情高涨。PK季期间,不仅各种玩法奖励丰厚,参与PK趣闻录活动,投稿自己在PK季遇到的趣事,还有机会带走...

测试谷歌VS Code AI 编程插件 Gemini Code Assist

用ClaudeSonnet3.7的天气测试编码,让谷歌VSCodeAI编程插件GeminiCodeAssist自动编程。生成的文件在浏览器中的效果如下:(附源代码)VSCode...

顾爷想知道第4.5期 国服便利性到底需优化啥?

前段时间DNF国服推出了名为“阿拉德B计划”的系列改版计划,截至目前我们已经看到了两项实装。不过关于便利性上,国服似乎还有很多路要走。自从顾爷回归DNF以来,几乎每天都在跟我抱怨关于DNF里面各种各样...

掌握Visual Studio项目配置【基础篇】

1.前言VisualStudio是Windows上最常用的C++集成开发环境之一,简称VS。VS功能十分强大,对应的,其配置系统较为复杂。不管是对于初学者还是有一定开发经验的开发者来说,捋清楚VS...

还嫌LED驱动设计套路深?那就来看看这篇文章吧

随着LED在各个领域的不同应用需求,LED驱动电路也在不断进步和发展。本文从LED的特性入手,推导出适合LED的电源驱动类型,再进一步介绍各类LED驱动设计。设计必读:LED四个关键特性特性一:非线...

Visual Studio Community 2022(VS2022)安装图文方法

直接上步骤:1,首先可以下载安装一个VisualStudio安装器,叫做VisualStudioinstaller。这个安装文件很小,很快就安装完成了。2,打开VisualStudioins...

Qt添加MSVC构建套件的方法(qt添加c++11)

前言有些时候,在Windows下因为某些需求需要使用MSVC编译器对程序进行编译,假设我们安装Qt的时候又只是安装了MingW构建套件,那么此时我们该如何给现有的Qt添加一个MSVC构建套件呢?本文以...

Qt为什么站稳c++GUI的top1(qt c)

为什么现在QT越来越成为c++界面编程的第一选择,从事QT编程多年,在这之前做C++界面都是基于MFC。当时为什么会从MFC转到QT?主要原因是MFC开发界面想做得好看一些十分困难,引用第三方基于MF...

qt开发IDE应该选择VS还是qt creator

如果一个公司选择了qt来开发自己的产品,在面临IDE的选择时会出现vs或者qtcreator,选择qt的IDE需要结合产品需求、部署平台、项目定位、程序猿本身和公司战略,因为大的软件产品需要明确IDE...

Qt 5.14.2超详细安装教程,不会来打我

Qt简介Qt(官方发音[kju:t],音同cute)是一个跨平台的C++开库,主要用来开发图形用户界面(GraphicalUserInterface,GUI)程序。Qt是纯C++开...

Cygwin配置与使用(四)——VI字体和颜色的配置

简介:VI的操作模式,基本上VI可以分为三种状态,分别是命令模式(commandmode)、插入模式(Insertmode)和底行模式(lastlinemode),各模式的功能区分如下:1)...

取消回复欢迎 发表评论: