Netty源码解析-EventLoop-DefaultEventLoop启动过程

Netty源码解析-EventLoop-DefaultEventLoop启动过程


Netty version : 4.1.53.Final
有任何错误或者建议可以留言交流,谢谢

DefaultEventLoop

DefaultEventLoop是EventLoop的一个最简单实现,为方便更好理解后面NioEventLoop做准备。

继承关系

在这里插入图片描述

DefaultEventLoop初始化

整个源码解析代码
从new DefaultEventLoop()开始进入
在这里插入图片描述
新建一个ThreadFactory对象,主要用来新建线程,同时传入的DefaultEventLoop.class用于帮助生成线程的命名。
在这里插入图片描述
到父类SingleThreadEventExecutor
在这里插入图片描述
这里新建了一个ThreadPerTaskExecutor对象,该类的主要作用是调用threadfactory的newThread()方法并启动线程
在这里插入图片描述
在调用父类的构造方法,一直跟踪代码到SingleThreadEventExecutor的构造方法
在这里插入图片描述
这里的addTaskWakesUp属性看意思是添加任务时将线程唤醒。
maxPendingTasks:最多可以有多少任务等待执行。不设置就是Integer.MAX_VALUE
下面赋值操作比较重要,进一步跟进
在这里插入图片描述
这个方法返回了一个exector势力,重写了execute方法,这个方法用于使用传入的commend触发executor(ThreadPerTaskExecutor)的execute方法,前面可以看到ThreadPerTaskExecutor的executor方法会新建线程同时执行start()方法。在进入apply方法
在这里插入图片描述
这里新建一个匿名任务,用于直接调用commend的run()方法。在返回到SingleThreadEventExecutor类,
在这里插入图片描述
这里我们知道了exector属性用来启动一个线程并执行一个任务,这里绕了几层。在后是初始化任务队列和拒绝策略。至此初始化工作大致完成

DefaultEventLoop提交任务

在这里插入图片描述

这里分析submit方法。进入代码一直到AbstractExecutorService的submit()方法
在这里插入图片描述
这里会执行execute方法,然后跟踪到SingleThreadEventExecutor的方法
在这里插入图片描述
这里判断inEventLoop也就是判断当前线程是不是和这个DefaultEventLoop实例绑定的线程。前面没有设置这个属性,所以返回为false,然后添加任务再进入if里面,在跟踪进入startThread方法
在这里插入图片描述
这里判断是否已经启动过,然后设置状态,然后进入doStartThread()方法代码如下:

   private void doStartThread() {
        assert thread == null;
        executor.execute(new Runnable() {
            @Override
            public void run() {
                thread = Thread.currentThread();
                if (interrupted) {
                    thread.interrupt();
                }

                boolean success = false;
                updateLastExecutionTime();
                try {
                    SingleThreadEventExecutor.this.run();
                    success = true;
                } catch (Throwable t) {
                    logger.warn("Unexpected exception from an event executor: ", t);
                } finally {
                    for (;;) {
                        int oldState = state;
                        if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet(
                                SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) {
                            break;
                        }
                    }

                    // Check if confirmShutdown() was called at the end of the loop.
                    if (success && gracefulShutdownStartTime == 0) {
                        if (logger.isErrorEnabled()) {
                            logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " +
                                    SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " +
                                    "be called before run() implementation terminates.");
                        }
                    }

                    try {
                        // Run all remaining tasks and shutdown hooks. At this point the event loop
                        // is in ST_SHUTTING_DOWN state still accepting tasks which is needed for
                        // graceful shutdown with quietPeriod.
                        for (;;) {
                            if (confirmShutdown()) {
                                break;
                            }
                        }

                        // Now we want to make sure no more tasks can be added from this point. This is
                        // achieved by switching the state. Any new tasks beyond this point will be rejected.
                        for (;;) {
                            int oldState = state;
                            if (oldState >= ST_SHUTDOWN || STATE_UPDATER.compareAndSet(
                                    SingleThreadEventExecutor.this, oldState, ST_SHUTDOWN)) {
                                break;
                            }
                        }

                        // We have the final set of tasks in the queue now, no more can be added, run all remaining.
                        // No need to loop here, this is the final pass.
                        confirmShutdown();
                    } finally {
                        try {
                            cleanup();
                        } finally {
                            // Lets remove all FastThreadLocals for the Thread as we are about to terminate and notify
                            // the future. The user may block on the future and once it unblocks the JVM may terminate
                            // and start unloading classes.
                            // See https://github.com/netty/netty/issues/6596.
                            FastThreadLocal.removeAll();

                            STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED);
                            threadLock.countDown();
                            int numUserTasks = drainTasks();
                            if (numUserTasks > 0 && logger.isWarnEnabled()) {
                                logger.warn("An event executor terminated with " +
                                        "non-empty task queue (" + numUserTasks + ')');
                            }
                            terminationFuture.setSuccess(null);
                        }
                    }
                }
            }
        });
    }

这里调用exector.execute方法并传入任务,这里这个exector就是前面初始化的时候exector,这个方法会创建一个线程来运行任务。所以进一步会到
在这里插入图片描述
这里apply方法再包装了一层并调用run()方法
在这里插入图片描述
再到start方法
在这里插入图片描述
这个时候我们通过idea调试切换到新建的线程
在这里插入图片描述
由于我之前在代码设置了断点 所有新建的线程停止在了断点处
在这里插入图片描述
在进入commend.run()方法,也就是之前贴上的代码:
在这里插入图片描述
这里绑定thread属性同时调用 SingleThreadEventExecutor.this.run();方法这个方法就是一个死循环,(finally里面的方法暂时还不知道具体意义暂时不分析)这个run方法也就是DefaultEventLoop重写的run()方法在这里插入图片描述
这里获取任务然后执行,如果任务为零,takeTask()方法将会阻塞,如下:

 protected Runnable takeTask() {
        assert inEventLoop();
        if (!(taskQueue instanceof BlockingQueue)) {
            throw new UnsupportedOperationException();
        }

        BlockingQueue<Runnable> taskQueue = (BlockingQueue<Runnable>) this.taskQueue;
        for (;;) {
            ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
            if (scheduledTask == null) {
                Runnable task = null;
                try {
                    task = taskQueue.take();
                    if (task == WAKEUP_TASK) {
                        task = null;
                    }
                } catch (InterruptedException e) {
                    // Ignore
                }
                return task;
            } else {
                long delayNanos = scheduledTask.delayNanos();
                Runnable task = null;
                if (delayNanos > 0) {
                    try {
                        task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS);
                    } catch (InterruptedException e) {
                        // Waken up.
                        return null;
                    }
                }
                if (task == null) {
                    // We need to fetch the scheduled tasks now as otherwise there may be a chance that
                    // scheduled tasks are never executed if there is always one task in the taskQueue.
                    // This is for example true for the read task of OIO Transport
                    // See https://github.com/netty/netty/issues/1614
                    fetchFromScheduledTaskQueue();
                    task = taskQueue.poll();
                }

                if (task != null) {
                    return task;
                }
            }
        }
    }

方法首先判断是否是绑定的线程,然后任务队列是BlockingQueue类型,没有任务将会阻塞,这里有两种任务队列,因为Default本身是实现了ScheduledExecutorService并实现了定时任务的运行,所以这里会从两个队列里面获取任务。

参考资料:
《Netty in action 》 v5
《Netty 4 核心原理》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
包含最新版文档以及全部jar包: jar包如下 netty-buffer-4.1.32.Final-sources.jar netty-buffer-4.1.32.Final.jar netty-build-22-sources.jar netty-build-22.jar netty-codec-4.1.32.Final-sources.jar netty-codec-4.1.32.Final.jar netty-codec-http-4.1.32.Final-sources.jar netty-codec-http-4.1.32.Final.jar netty-codec-http2-4.1.32.Final-sources.jar netty-codec-http2-4.1.32.Final.jar netty-codec-memcache-4.1.32.Final-sources.jar netty-codec-memcache-4.1.32.Final.jar netty-codec-redis-4.1.32.Final-sources.jar netty-codec-redis-4.1.32.Final.jar netty-codec-socks-4.1.32.Final-sources.jar netty-codec-socks-4.1.32.Final.jar netty-codec-stomp-4.1.32.Final-sources.jar netty-codec-stomp-4.1.32.Final.jar netty-common-4.1.32.Final-sources.jar netty-common-4.1.32.Final.jar netty-example-4.1.32.Final-sources.jar netty-example-4.1.32.Final.jar netty-handler-4.1.32.Final-sources.jar netty-handler-4.1.32.Final.jar netty-handler-proxy-4.1.32.Final-sources.jar netty-handler-proxy-4.1.32.Final.jar netty-resolver-4.1.32.Final-sources.jar netty-resolver-4.1.32.Final.jar netty-tcnative-2.0.20.Final-osx-x86_64.jar netty-tcnative-2.0.20.Final-sources.jar netty-transport-4.1.32.Final-sources.jar netty-transport-4.1.32.Final.jar netty-transport-native-epoll-4.1.32.Final-linux-x86_64.jar netty-transport-native-epoll-4.1.32.Final-sources.jar netty-transport-native-kqueue-4.1.32.Final-osx-x86_64.jar netty-transport-native-kqueue-4.1.32.Final-sources.jar netty-transport-native-unix-common-4.1.32.Final-sources.jar netty-transport-native-unix-common-4.1.32.Final.jar netty-transport-rxtx-4.1.32.Final-sources.jar netty-transport-rxtx-4.1.32.Final.jar netty-transport-sctp-4.1.32.Final-sources.jar netty-transport-sctp-4.1.32.Final.jar netty-transport-udt-4.1.32.Final-sources.jar netty-transport-udt-4.1.32.Final.jar

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值