<2021SC@SDUSC>NioEventLoopGroup创建过程(二)

2021SC@SDUSC

一、前言

在上一篇博客中,主要分析了NioEventLoopGroup创建过程中的大体过程。在本篇博客中,将会分析一些创建过程中的细节,包括NioEventLoopGroup类中的newChild()方法,创建失败后的关闭过程,以及一些其它的工作。

二、newChild(Executor executor, Object… args)

在上一篇博客的分析中,发现NioEventLoopGroup其实是线程池,而在内部,有属性children,是EventExecutor数组,继承自MultithreadEventExecutorGroup。另外,也知道了创建过程的大部分都是在MultithreadEventExecutorGroup内完成的。在MultithreadEventExecutorGroup类的构造方法中,有一个for循环,用于初始化每一个线程。

children[i] = newChild(executor, args);
success = true;

在try语句块内,主要就是完成线程的创建。而newChild方法是一个抽象方法,其实现推迟到子类中完成。

protected abstract EventExecutor newChild(Executor executor, Object... args) throws Exception;

在debug运行后,发现,newChild的工作由NioEventLoopGroup完成。

    @Override
    protected EventLoop newChild(Executor executor, Object... args) throws Exception {
        SelectorProvider selectorProvider = (SelectorProvider) args[0];
        SelectStrategyFactory selectStrategyFactory = (SelectStrategyFactory) args[1];
        RejectedExecutionHandler rejectedExecutionHandler = (RejectedExecutionHandler) args[2];
        EventLoopTaskQueueFactory taskQueueFactory = null;
        EventLoopTaskQueueFactory tailTaskQueueFactory = null;

        int argsLength = args.length;
        if (argsLength > 3) {
            taskQueueFactory = (EventLoopTaskQueueFactory) args[3];
        }
        if (argsLength > 4) {
            tailTaskQueueFactory = (EventLoopTaskQueueFactory) args[4];
        }
        return new NioEventLoop(this, executor, selectorProvider,
                selectStrategyFactory.newSelectStrategy(),
                rejectedExecutionHandler, taskQueueFactory, tailTaskQueueFactory);
    }

可以看见,在newChild方法中,首先是取出了args中的参数,回顾上一篇博客中的内容,知道,在这里,args长度为3,也就是说,只有SelectorProvider,SelectStrategyFactory,RejectedExecutionHandler三个变量。之后,在创建NioEventLoop变量,并返回,可知,children数组中每一个内容的真实类型是NioEventLoop。

三、失败后关闭线程

在之前的分析中,每一个线程创建成功后,就会将success设置为true,而在for循环里,还有catch,finally语句块,其中catch语句块负责在捕获到异常后,抛出IllegalStateException。

catch (Exception e) {
	// TODO: Think about if this is a good exception type
    throw new IllegalStateException("failed to create a child event loop", e);
}

可以看到,在注释中,写道,思考IllegalStateException是否是一个合适的异常类型,我能力有限,无法理解这个类型会引起什么问题,希望有人能在评论中给出答案。
之后,是finally’语句块。

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;
        	}
		}
	}
}

无论是否出现异常,都会进入finally语句块,在语句块中,首先对[0, i)的线程进行关闭,使用方法shutdownGracefully,注意,就像前面分析的children[j]的真实类型是NioEventLoop,而在NioEventLoop中,没有shutdownGracefully,在AbstractEventExecutor中找到,其实现了EventExecutor接口。

    @Override
    public Future<?> shutdownGracefully() {
        return shutdownGracefully(DEFAULT_SHUTDOWN_QUIET_PERIOD, DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
    }
    static final long DEFAULT_SHUTDOWN_QUIET_PERIOD = 2;
    static final long DEFAULT_SHUTDOWN_TIMEOUT = 15;

在AbstractEventExecutor的静态变量中找到对于DEFAULT_SHUTDOWN_QUIET_PERIOD,DEFAULT_SHUTDOWN_TIMEOUT的初始化,而shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit)方法定义在EventExecutorGroup接口中,其为EventExecutor的父接口。而方法的实现推迟到SingleThreadEventExecutor中,具体实现就不详细解释。
在这里插入图片描述
图片为NioEventLoop的继承树。
在完成了对线程的关闭之后,看到还有另外一个for循环。

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;
  	}
}

在这个for循环中,判断每一个线程是否关闭,如果没有,等待知到它关闭,之后,再同样处理下一个线程,知到所有线程关闭。之所以这样做,是因为在netty框架中许多操作都是异步的,即在调用,一般都会直接返回Future对象,实际上,处理可能还么有完成,等到需要使用返回的结果时,再去Future中获取,当然,一般情况下,调用的方法都已经完成了。

四、其它

        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);
        }

在完成了对与children的初始化后,会进入上面代码的部分,在这之中,首先会创建一个future监听器,用于监听线程关闭,如果,则会触发监听器,而terminatedChildren是一个AtomicInteger,保证线程安全。
再将创建好的监听器添加到所有线程上。

五、总结

在本篇博客中,分析了上一篇博客中遗留的一些细节,包括创建线程的过程,以及出现异常时,对线程进行关闭处理,最后还有添加future。
当然,由于能力有限,对于很多问题无法深入分析,但,大体上,NioEventLoopGroup的创建过程都由涉及,关于它的创建,应该就写到这了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东羚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值