Netty源码解析(四)之EventLoop和EventLoopGroup

如何优雅地停止长连接网关服务 优雅地停止服务,也就是要保证把没有处理完的工作处理完成。比如停止一些依赖的服务,输出一些日志,发一些信号给其他的应用系统等,这个在保证系统的高可用中是非常有必要的。 尤其像长连接网关这种,管理了大量的TCP 连接,绝不能直接暴力关闭,必须要保证已有的任务全都处理完,并且在关闭的过程中不会有新的请求进来。 本文以开源项目SONA为例,详细解析网关服务优雅的原理和实现,帮助读者更好理解和实践。本文最后附上开源项目地址。 阅读详情

前面几篇文章对Netty的服务器启动以及客户端连接做了较为详细的解析,这样大家应该对Netty有了一个比较全面、宏观的了解。接下来的文章,我将对Netty的各个主要的组件进行源码分析。我个人认为,这种先宏观再细节,从面到点的顺序是比较科学的。这篇文章我会先介绍EventLoop和EventLoopGroup。

一. EventLoopGroup和EventExecutorGroup

前面说过很多次,EventLoopGroup其实就相当于一个线程池,带着这样一个概念,我们来看一下EventLoopGroup的主要方法(包括其从父接口EventExecutorGroup继承的方法)。

  • EventLoop next();

该方法返回下一个将要使用的EventLoop,相当于线程池返回下一个用来处理任务的线程。

  • ChannelFuture register(Channel channel);

通过该方法将一个Channel注册(或者说绑定)到某个EventLoop上,一个Channel在其生命周期内只会绑定到一个EventLoop上(但一个EventLoop可以绑定多个Channel),这样这个Channel后续的IO事件都会交由这个EventLoop来处理,因此Netty可以保证Channel一定是线程安全的。

  • Future<?> shutdownGracefully();
  • boolean isShuttingDown();
  • void shutdown();

这三个方法都是继承自父接口EventExecutorGroup。shutdownGracefully()方法可以“优雅地”关闭EventLoopGroup,所谓优雅,就是能保证在调用该方法之前提交给EventLoopGroup的任务都可以执行,也就是说会在执行完剩余的任务后才会真正关闭,该方法是异步的,因此返回一个Future。与这个方法相对应的是shutdown()方法,他则不能保证剩余的任务能执行完毕(这个方法在4.1.47版本已经过时了)。isShuttingDown()只有在两种情况下返回true,1. 该EventLoopGroup的所有EventLoop都已经关闭;2. 该EventLoopGroup调用了shutdownGracefully()方法,正在关闭的过程中。

  • Future<?> submit(Runnable task);
  • ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
  • ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
  • ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);

这几个方法也是继承自父接口EventExecutorGroup,从方法名上也可以看出他们的功能,向EventLoopGroup提交一个普通任务,或定时任务,或延时任务。关于这几个方法的详细解释可以去看 java.util.concurrent.ScheduledExecutorService中的注释说明,这里不再赘述。

我们可以这样理解EventLoopGroup和EventExecutorGroup:EventExecutorGroup相当于一个通用的可以执行各种类型的任务的线程池,并且能对线程池进行生命周期的管理,而EventLoopGroup则是在此基础上专门用来处理Channel的IO任务的线程池。

说完了接口方法,接下来看一些主要的EventLoopGroup的子类是如何实现这些接口方法的。

MultithreadEventExecutorGroup

MultithreadEventExecutorGroup有两个重要的成员变量children和chooser,children是一个类型为EventExecutor的数组,相当于线程池里的线程数组,chooser则是用来选择下一个将要使用的EventExecutor的选择器。

private final EventExecutor[] children;

private final EventExecutorChooserFactory.EventExecutorChooser chooser;

 MultithreadEventExecutorGroup的构造方法如下,方法的逻辑很简单,首先会实例化一个ThreadPerTaskExecutor,然后循环调用newChild()方法得到每一个child,然后再通过chooserFactory得到chooser,这样MultithreadEventExecutorGroup最重要的两个成员变量就得到了。

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) {
            // TODO: Think about if this is a good exception type
            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);
}

MultithreadEventExecutorGroup的newChild()方法是一个抽象方法,需要交给子类来实现。那么我们就来看一下NioEventLoopGroup,他的newChild()方法就是实例化一个NioEventLoop,至于那些参数在后面讲NioEventLoop的时候再详细介绍。NioEventLoopGroup的execute()方法继承自AbstractEventExecutorGroup,逻辑就是将任务交由下一个要使用的EventLoop来处理,NioEventLoopGroup的register()方法继承自MultithreadEventLoopGroup,逻辑也差不多,也是将channel的register操作交由EventLoop来处理。

//NioEventLoopGroup.java
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);
}


//AbstractEventExecutorGroup.java
public void execute(Runnable command) {
    next().execute(command);
}

//MultithreadEventExecutorGroup.java
public EventExecutor next() {
    return chooser.next();
}


//MultithreadEventLoopGroup.java
public ChannelFuture register(Channel channel) {
    return next().register(channel);
}

至此,我们可以总结一下EventLoopGroup的整体逻辑,他相当于一个专门用来处理Channel的IO操作的线程池,他的内部有一个children数组和一个选择器chooser,EventLoopGroup在实例化的时候,会调用newChild()方法创建每一个EventLoop,Channel可以通过register()方法将自身绑定到某一个EventLoop上。EventLoopGroup通过调用next()方法来选择一个EventLoop,而next()方法则返回通过选择器chooser的策略选择出来的EventLoop(或者说EventExecutor)。

二. EventLoop和EventExecutor

上一节说了EventLoopGroup和EventExecutorGroup的关系和区别,那么对于EventLoop和EventExecutor来说其实也是一样的。其实在大多数语义下,不需要对EventLoop和EventExecutor二者进行区分,可以把他们两个看作同一个东西。

  • EventExecutor next();

 没错,EventExecutor也有next()方法,不过他的next()方法只是返回一个自身的引用

  •  EventExecutorGroup parent();

 返回该EventExecutor所属的EventExecutorGroup

  • boolean inEventLoop();

 判断当前线程是否是该EventLoop线程

接口方法比较简单,我们主要还是关心实现类是怎么实现这些功能的,这也是这篇文章的重点。

NioEventLoop

NioEventLoop是使用Netty的用户见的最多的EventLoop,我们主要说一下他的逻辑。

  • public ChannelFuture register(Channel channel)

NioEventLoop本身并不处理Channel的注册操作,具体的操作还是交由Channel自身来完成,这一块之前在讲Netty服务器启动的文章中详细说过了

Netty源码解析(二)之服务器启动源码_benjam1n77的博客-CSDN博客

NioEventLoop所完成的工作仅仅是将channel注册的结果封装为一个ChannelFuture而已。

@Override
public ChannelFuture register(Channel channel) {
    return register(new DefaultChannelPromise(channel, this));
}

@Override
public ChannelFuture register(final ChannelPromise promise) {
    ObjectUtil.checkNotNull(promise, "promise");
    promise.channel().unsafe().register(this, promise);
    return promise;
}
  • private void execute(Runnable task, boolean immediate) 

execute()方法的逻辑是NioEventLoop最核心的部分,他继承自SingleThreadEventExecutor。当我们调用execute()方法向NioEventLoop提交一个 任务(Runnable)时,会将这个任务加入到队列中,SingleThreadEventExecutor有一个任务队列,用来存储递交给他的task。

private final Queue<Runnable> taskQueue;

然后,如果调用execute()方法的线程不是NioEventLoop自身的线程(inEventLoop()方法返回false),那么则会调用startThread()方法,值得注意的是,如果第一次向一个NioEventLoop提交任务时,那么startThread()方法必被调用,因为第一次调用execute()方法必然是外部线程调用,不会是NioEventLoop自身的线程调用。

private void execute(Runnable task, boolean immediate) {
    boolean inEventLoop = inEventLoop();
    addTask(task);
    if (!inEventLoop) {
        startThread();
        if (isShutdown()) {
            boolean reject = false;
            try {
                if (removeTask(task)) {
                    reject = true;
                }
            } catch (UnsupportedOperationException e) {
                // The task queue does not support removal so the best thing we can do is to just move on and
                // hope we will be able to pick-up the task before its completely terminated.
                // In worst case we will log on termination.
            }
            if (reject) {
                reject();
            }
        }
    }

    if (!addTaskWakesUp && immediate) {
        wakeup(inEventLoop);
    }
}
  •  private void startThread()

 startThread()方法逻辑很简单,如果EventLoop的状态为ST_NOT_STARTED,那么将状态设置为ST_STARTED,然后调用doStartThread()方法开启线程。也就是说doStartThread()方法只会调用一次,即第一次向EventLoop提交任务的时候,他相当于一个初始化方法。

EventLoop的生命周期有如下几种状态:

  1.  ST_NOT_STARTED:EventLoop还未开始工作
  2.  ST_STARTED:EventLoop已经开始正常工作,可以向其正常地提交任务
  3.  ST_SHUTTING_DOWN:调用shutdownGracefully()后状态变为ST_SHUTTING_DOWN,此时仍然还是可以向EventLoop提交任务。
  4. ST_SHUTDOWN:执行完队列中的剩余任务,并且执行完runShutdownHooks()方法后,状态变为ST_SHUTDOWN,此时已经不能向EventLoop提交任务了(在钩子方法中提交任务除外),但并不意味着任务队列中的所有任务全部执行完了,因为有可能在钩子方法中又提交了新的任务。
  5. ST_TERMINATED:EventLoop中的所有任务全部完成了,selector也已经关闭了(如果是NioEventLoop的话)。

 注意,从ST_SHUTTING_DOWN到ST_SHUTDOWN和从ST_SHUTDOWN到ST_TERMINATED两次调用confirmShutDown()方法是不一样的,前者调用confirmShutDown()方法时,是可以在钩子方法中添加任务,而后者调用confirmShutDown()方法时,仅执行完队列中剩余的任务,不能再添加新的任务。confirmShutDown()方法会在文章后面进行更详细的解析,这里我们先暂时放下。

private void startThread() {
    if (state == ST_NOT_STARTED) {
        if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_STARTED)) {
            boolean success = false;
            try {
                doStartThread();
                success = true;
            } finally {
                if (!success) {
                    STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_NOT_STARTED);
                }
            }
        }
    }
}
  • private void doStartThread()

NioEventLoop调用doStartThread()方法开始执行任务,该方法调用自身内部的executor来执行一个匿名Runnable,这个executor才是真正执行任务的executor,EventLoop其实是对这个executor的一个包装。这个匿名Runnable的run()方法的主要逻辑是这样的:

  1. 首先保存该EventLoop底层所用到的线程。
  2. 调用SingleThreadEventExecutor.run()方法,该方法是SingleThreadEventExecutor的抽象方法,需要子类来实现。通常来说,这个方法会在一个死循环中不断从任务队列中取任务来执行。我们接下来会分析NioEventLoop.run()。
  3. run()方法执行结束,这意味着该EventLoop应该停止工作了,他的生命周期至少走到了ST_SHUTTING_DOWN这一步,后续的操作全部都是处理EventLoop的shutdown操作。shutdown的逻辑我们在前面也已经叙述过了。
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);
                    }
                }
            }
        }
    });
}
  • protected void run()

 run()方法是SingleThreadEventExecutor定义的一个抽象方法,这里我们讲的是NioEventLoop的实现,run()方法是NioEventLoop最核心的一个方法。run()方法在一个死循环中,他会周而复始地做以下几件事情:

  1. 调用selector.select()或selectNow()判断是否有IO事件任务
  2. 如果有,则调用processSelectedKeys()处理IO事件任务
  3. 再调用runAllTasks()处理其他任务

protected void run() {
    int selectCnt = 0;
    for (;;) {
        try {
            int strategy;
            try {
                strategy = selectStrategy.calculateStrategy(selectNowSupplier, hasTasks());
                switch (strategy) {
                    case SelectStrategy.CONTINUE:
                        continue;

                    case SelectStrategy.BUSY_WAIT:
                        // fall-through to SELECT since the busy-wait is not supported with NIO

                    case SelectStrategy.SELECT:
                        long curDeadlineNanos = nextScheduledTaskDeadlineNanos();
                        if (curDeadlineNanos == -1L) {
                            curDeadlineNanos = NONE; // nothing on the calendar
                        }
                        nextWakeupNanos.set(curDeadlineNanos);
                        try {
                            if (!hasTasks()) {
                                strategy = select(curDeadlineNanos);
                            }
                        } finally {
                            // This update is just to help block unnecessary selector wakeups
                            // so use of lazySet is ok (no race condition)
                            nextWakeupNanos.lazySet(AWAKE);
                        }
                        // fall through
                    default:
                }
            } catch (IOException e) {
                // If we receive an IOException here its because the Selector is messed up. Let's rebuild
                // the selector and retry. https://github.com/netty/netty/issues/8566
                rebuildSelector0();
                selectCnt = 0;
                handleLoopException(e);
                continue;
            }

            selectCnt++;
            cancelledKeys = 0;
            needsToSelectAgain = false;
            final int ioRatio = this.ioRatio;
            boolean ranTasks;
            if (ioRatio == 100) {
                try {
                    if (strategy > 0) {
                        processSelectedKeys();
                    }
                } finally {
                    // Ensure we always run tasks.
                    ranTasks = runAllTasks();
                }
            } else if (strategy > 0) {
                final long ioStartTime = System.nanoTime();
                try {
                    processSelectedKeys();
                } finally {
                    // Ensure we always run tasks.
                    final long ioTime = System.nanoTime() - ioStartTime;
                    ranTasks = runAllTasks(ioTime * (100 - ioRatio) / ioRatio);
                }
            } else {
                ranTasks = runAllTasks(0); // This will run the minimum number of tasks
            }

            if (ranTasks || strategy > 0) {
                if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS && logger.isDebugEnabled()) {
                    logger.debug("Selector.select() returned prematurely {} times in a row for Selector {}.",
                            selectCnt - 1, selector);
                }
                selectCnt = 0;
            } else if (unexpectedSelectorWakeup(selectCnt)) { // Unexpected wakeup (unusual case)
                selectCnt = 0;
            }
        } catch (CancelledKeyException e) {
            // Harmless exception - log anyway
            if (logger.isDebugEnabled()) {
                logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector {} - JDK bug?",
                        selector, e);
            }
        } catch (Throwable t) {
            handleLoopException(t);
        }
        // Always handle shutdown even if the loop processing threw an exception.
        try {
            if (isShuttingDown()) {
                closeAll();
                if (confirmShutdown()) {
                    return;
                }
            }
        } catch (Throwable t) {
            handleLoopException(t);
        }
    }
}

我们接下来再一步步详细地解释

1. 获取selectStrategy

selectStrategy.calculateStrategy(selectNowSupplier, hasTasks())

 这一步是获取selectStrategy,如果队列中没有任务,则返回SelectStrategy.SELECT,如果没有任务,则调用selectNow()并返回结果。

public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception {
    return hasTasks ? selectSupplier.get() : SelectStrategy.SELECT;
}



private final IntSupplier selectNowSupplier = new IntSupplier() {
    @Override
    public int get() throws Exception {
        return selectNow();
    }
};

 2. select或selectNow

try {
    switch (strategy) {
        case SelectStrategy.CONTINUE:
            continue;

        case SelectStrategy.BUSY_WAIT:
            // fall-through to SELECT since the busy-wait is not supported with NIO

        case SelectStrategy.SELECT:
            long curDeadlineNanos = nextScheduledTaskDeadlineNanos();
            if (curDeadlineNanos == -1L) {
                curDeadlineNanos = NONE; // nothing on the calendar
            }
            nextWakeupNanos.set(curDeadlineNanos);
            try {
                if (!hasTasks()) {
                    strategy = select(curDeadlineNanos);
                }
            } finally {
                // This update is just to help block unnecessary selector wakeups
                // so use of lazySet is ok (no race condition)
                nextWakeupNanos.lazySet(AWAKE);
            }
// fall through
        default:
    }
}

SelectStrategy有三种值:

  • SelectStrategy.CONTINUE (-2) : 跳过这次循环
  • SelectStrategy.BUSY_WAIT (-3) : 忙等,非阻塞式地获取IO事件,在NioEventLoop中不支持
  • SelectStrategy.SELECT (-1) : 进行一次select

当任务队列中还有任务时,selectStrategy为selectNow()返回的值,不等于上面任何一种情况;没有任务时, selectStrategy为SelectStrategy.SELECT,然后会根据curDeadlineNanos来判断调用哪一个select方法。

  1. 没有定时任务,调用selector.select(),因为该方法是阻塞式的,因此如果一直没有IO事件发生,线程会阻塞在这里。
  2. 有定时任务,并且定时任务的截止时间小于5微秒,说明马上有定时任务要执行,线程不需要阻塞,因此调用selector.selectNow()。
  3. 有定时任务,并且定时任务的截止时间大于5微妙,则调用selector.select(timeOutMillis),只需要保证在截止时间之前线程能及时醒来即可。
private int select(long deadlineNanos) throws IOException {
    if (deadlineNanos == NONE) {
        return selector.select();
    }
    // Timeout will only be 0 if deadline is within 5 microsecs
    long timeoutMillis = deadlineToDelayNanos(deadlineNanos + 995000L) / 1000000L;
    return timeoutMillis <= 0 ? selector.selectNow() : selector.select(timeoutMillis);
}

 此外,我们需要注意一件事情,即如果NioEventLoop的任务队列中没有普通任务且定时任务的截止时间很久远或者没有定时任务,那么调用selector.select()会阻塞线程,直到有IO事件的发生。那么在线程阻塞期间如果提交新任务,是否该任务会因为线程阻塞而一直得不到执行呢?事实上并不会,因为当调用addTask(Runnable task)方法提交任务时,是可以将线程唤醒的,代码如下。

public void execute(Runnable task) {
    ObjectUtil.checkNotNull(task, "task");
    //如果task不是一个LazyRunnable类型的task,则第二个传递的参数为true
    execute(task, !(task instanceof LazyRunnable) && wakesUpForTask(task));
}

//这个方法总是返回true,当然子类可以对这个方法进行重写,但NioEventLoop并没有重写
protected boolean wakesUpForTask(Runnable task) {
    return true;
}

private void execute(Runnable task, boolean immediate) {
    boolean inEventLoop = inEventLoop();
    addTask(task);
    if (!inEventLoop) {
        startThread();
        if (isShutdown()) {
            boolean reject = false;
            try {
                if (removeTask(task)) {
                    reject = true;
                }
            } catch (UnsupportedOperationException e) {
                // The task queue does not support removal so the best thing we can do is to just move on and
                // hope we will be able to pick-up the task before its completely terminated.
                // In worst case we will log on termination.
            }
            if (reject) {
                reject();
            }
        }
    }
    //对NioEventLoop,addTaskWakesUp参数默认为false,因此immediate如果为true,则会在把任务加入到队列后调用wakeup方法
    if (!addTaskWakesUp && immediate) {
        wakeup(inEventLoop);
    }
}


protected void wakeup(boolean inEventLoop) {
    if (!inEventLoop && nextWakeupNanos.getAndSet(AWAKE) != AWAKE) {
        selector.wakeup();
    }
}

3. 如果发生异常,则需要重建selector

这一块没啥说的,就是调用rebuildSelector0()方法重建一个selector。rebuildSelector0()方法的逻辑也不复杂,就是重新open一个新的selector,并且关闭旧的selector,这里不多赘述。

catch(IOException e){
    // If we receive an IOException here its because the Selector is messed up. Let's rebuild
    // the selector and retry. https://github.com/netty/netty/issues/8566
    rebuildSelector0();
    selectCnt = 0;
    handleLoopException(e);
    continue;
}

4. 执行IO任务和普通任务

判断ioRatio的值,这个值表示的是NioEventLoop用来执行IO任务和执行普通任务的时间的比例,如果这个值越小,那么用来执行普通任务的时间就越多。例如,如果ioRatio=20,那么执行IO任务和执行普通任务的时间比例为20:80,即1:4。默认情况下,ioRatio=50。此外,如果ioRatio=100,则在执行完IO任务后会执行所有的普通任务,而不管他花费了多少时间。

selectCnt++;
cancelledKeys = 0;
needsToSelectAgain = false;
final int ioRatio = this.ioRatio;
boolean ranTasks;
if (ioRatio == 100) {
    try {
        if (strategy > 0) {
            processSelectedKeys();
        }
    } finally {
        // Ensure we always run tasks.
        //ioRatio为100,调用不带参的runAllTasks()方法,执行队列中的所有任务,不管他们需要花费多少时间
        ranTasks = runAllTasks();   
    }
} else if (strategy > 0) {
    final long ioStartTime = System.nanoTime();
    try {
        //执行IO任务
        processSelectedKeys();
    } finally {
        // Ensure we always run tasks.
        final long ioTime = System.nanoTime() - ioStartTime;
        //执行普通任务,这里调用带参的runAllTasks方法,该方法可以保证在规定时间内返回,即使队列中还存在任务没有执行,也不会继续执行了
        ranTasks = runAllTasks(ioTime * (100 - ioRatio) / ioRatio);
    }
} else {
    //没有IO任务,那么就只执行最少数量的普通任务。(最少数量为64)
    ranTasks = runAllTasks(0); // This will run the minimum number of tasks
}

if (ranTasks || strategy > 0) {
    if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS && logger.isDebugEnabled()) {
        logger.debug("Selector.select() returned prematurely {} times in a row for Selector {}.",
                selectCnt - 1, selector);
    }
    selectCnt = 0;
} else if (unexpectedSelectorWakeup(selectCnt)) { // Unexpected wakeup (unusual case)
    selectCnt = 0;
}

5. 关闭NioEventLoop

每次循环的最后,都会判断NioEventLoop的状态,如果isShuttingDown()返回true,则说明某个线程调用了shutdownGracefully(),也即意味着该NioEventLoop将要被关闭了,那么就调用closeAll()关闭所有的SelectionKey和Channel。最后再调用一次confirmShutdown()确认是否真正的要关闭,如果是,那么run()方法返回,循环结束。

try {
    if (isShuttingDown()) {
        closeAll();
        if (confirmShutdown()) {
            return;
        }
    }
} catch (Throwable t) {
    handleLoopException(t);
}

至此,NioEventLoop的run()方法的逻辑已经讲完了,这里还剩下两个比较重要的方法。processSelectedKeys():处理IO任务;runAllTasks():处理普通任务。

  • private void processSelectedKeys()

该方法会根据selectedKeys是否为null来调用processSelectedKeysOptimized()或processSelectedKeysPlain(),selectedKeys是NioEventLoop对JDK NIO原生的SelectionKey做的优化,selector.selectedKeys()返回的是一个Set<SelectionKey>,而这里的selectedKeys是一个SelectionKey数组,相比于Set,数组的遍历速度肯定更快。

private void processSelectedKeys() {
    if (selectedKeys != null) {
        processSelectedKeysOptimized();
    } else {
        processSelectedKeysPlain(selector.selectedKeys());
    }
}
  •  private void processSelectedKeysOptimized()

在循环中调用processSelectedKey()依次处理所有的selectedKey,每次循环的最后都会检查一下needsToSelectAgain,如果为true,则需要reset selectedKeys并重新调用一次selectNow()。needsToSelectAgain只会在有多次selectedKey被cancelled的情况出现才会设置为true。

private void processSelectedKeysOptimized() {
    for (int i = 0; i < selectedKeys.size; ++i) {
        final SelectionKey k = selectedKeys.keys[i];
        // null out entry in the array to allow to have it GC'ed once the Channel close
        // See https://github.com/netty/netty/issues/2363
        selectedKeys.keys[i] = null;

        final Object a = k.attachment();

        if (a instanceof AbstractNioChannel) {
            processSelectedKey(k, (AbstractNioChannel) a);
        } else {
            @SuppressWarnings("unchecked")
            NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
            processSelectedKey(k, task);
        }

        if (needsToSelectAgain) {
            // null out entries in the array to allow to have it GC'ed once the Channel close
            // See https://github.com/netty/netty/issues/2363
            selectedKeys.reset(i + 1);

            selectAgain();
            i = -1;
        }
    }
}


private void selectAgain() {
    needsToSelectAgain = false;
    try {
        selector.selectNow();
    } catch (Throwable t) {
        logger.warn("Failed to update SelectionKeys.", t);
    }
}
  •  private void processSelectedKey(SelectionKey k, AbstractNioChannel ch)

 这里先判断selectionKey是否valid,如果selectionKey不是valid且相应的channel仍然注册在该EventLoop上,那么应该关闭该channel,如果channel已经不注册在这个EventLoop上,那么显然在这里是无权关闭这个channel的。

接下来判断IO事件的类型,然后调用channel的unsafe的响应的方法。如果为OP_CONNETC,调用unsafe.finishConnect(),并且取消注册的OP_CONNETC事件,否则可能导致JDK的空轮询BUG;如果为OP_WIRITE,调用unsafe().forceFlush();如果为OP_ACCEPT或者OP_READ,调用unsafe.read()。

private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
    final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe();
    if (!k.isValid()) {
        final EventLoop eventLoop;
        try {
            eventLoop = ch.eventLoop();
        } catch (Throwable ignored) {
            // If the channel implementation throws an exception because there is no event loop, we ignore this
            // because we are only trying to determine if ch is registered to this event loop and thus has authority
            // to close ch.
            return;
        }
        // Only close ch if ch is still registered to this EventLoop. ch could have deregistered from the event loop
        // and thus the SelectionKey could be cancelled as part of the deregistration process, but the channel is
        // still healthy and should not be closed.
        // See https://github.com/netty/netty/issues/5125
        if (eventLoop == this) {
            // close the channel if the key is not valid anymore
            unsafe.close(unsafe.voidPromise());
        }
        return;
    }

    try {
        int readyOps = k.readyOps();
        // We first need to call finishConnect() before try to trigger a read(...) or write(...) as otherwise
        // the NIO JDK channel implementation may throw a NotYetConnectedException.
        if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
            // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
            // See https://github.com/netty/netty/issues/924
            int ops = k.interestOps();
            ops &= ~SelectionKey.OP_CONNECT;
            k.interestOps(ops);

            unsafe.finishConnect();
        }

        // Process OP_WRITE first as we may be able to write some queued buffers and so free memory.
        if ((readyOps & SelectionKey.OP_WRITE) != 0) {
            // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
            ch.unsafe().forceFlush();
        }

        // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
        // to a spin loop
        if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
            unsafe.read();
        }
    } catch (CancelledKeyException ignored) {
        unsafe.close(unsafe.voidPromise());
    }
}
  • protected boolean runAllTasks() 和 protected boolean runAllTasks(long timeoutNanos)  

 无参的runAllTasks方法会执行完任务队列中的全部任务,带timeoutNanos参数的runAllTasks方法只会执行一定的时间,如果超过这个时间,那么该方法return,队列中剩余的任务就不执行了。

在无参的runAllTasks()方法中,会一直从定时任务队列中取定时任务加入到普通任务队列中,然后执行普通队列中的所有任务,直到fetchFromScheduledTaskQueue()方法返回true。最后再调用一次afterRunningAllTasks()方法。

protected boolean runAllTasks() {
    assert inEventLoop();
    boolean fetchedAll;
    boolean ranAtLeastOne = false;

    do {
        fetchedAll = fetchFromScheduledTaskQueue();
        if (runAllTasksFrom(taskQueue)) {
            ranAtLeastOne = true;
        }
    } while (!fetchedAll); // keep on processing until we fetched all scheduled tasks.

    if (ranAtLeastOne) {
        lastExecutionTime = ScheduledFutureTask.nanoTime();
    }
    afterRunningAllTasks();
    return ranAtLeastOne;
}

 fetchFromScheduledTaskQueue()方法逻辑为,一直从定时任务队列中取满足执行条件的任务到普通队列中,直到普通队列已经满了或者定时任务队列中没有需要执行的任务了,如果是前者,返回false,后者返回true。

private boolean fetchFromScheduledTaskQueue() {
    //定时任务队列为空,没有定时任务,直接返回true
    if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) {
        return true;
    }
    long nanoTime = AbstractScheduledEventExecutor.nanoTime();
    for (;;) {
        //取已经满足执行时间的定时任务
        Runnable scheduledTask = pollScheduledTask(nanoTime);
        if (scheduledTask == null) {
            //没有的话,直接返回true
            return true;
        }
        if (!taskQueue.offer(scheduledTask)) {
            //将需要执行的定时任务加入到普通任务队列中,如果普通任务队列已经满了,返回false,意味着还需要继续调用该方法
            // No space left in the task queue add it back to the scheduledTaskQueue so we pick it up again.
            scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask);
            return false;
        }
    }
}

带参的runAllTasks()方法唯一不同的是,每执行64个任务就会检查一次是否超时,如果超时了,就不继续执行任务了,直接返回。 

protected boolean runAllTasks(long timeoutNanos) {
    fetchFromScheduledTaskQueue();
    Runnable task = pollTask();
    if (task == null) {
        afterRunningAllTasks();
        return false;
    }

    final long deadline = timeoutNanos > 0 ? ScheduledFutureTask.nanoTime() + timeoutNanos : 0;
    long runTasks = 0;
    long lastExecutionTime;
    for (;;) {
        safeExecute(task);

        runTasks ++;

        // Check timeout every 64 tasks because nanoTime() is relatively expensive.
        // XXX: Hard-coded value - will make it configurable if it is really a problem.
        if ((runTasks & 0x3F) == 0) {
            lastExecutionTime = ScheduledFutureTask.nanoTime();
            if (lastExecutionTime >= deadline) {
                break;
            }
        }

        task = pollTask();
        if (task == null) {
            lastExecutionTime = ScheduledFutureTask.nanoTime();
            break;
        }
    }

    afterRunningAllTasks();
    this.lastExecutionTime = lastExecutionTime;
    return true;
}

(完)

Netty EventLoopGroup 详解:Nio、Epoll、Poll 、KQueue和IoUring Netty 是一个高性能的网络通信框架,它使用 EventLoopGroup 来处理 I/O 事件。不同的 EventLoopGroup 实现针对不同的操作系统和应用场景优化性能。和,并提供了详细的代码示例和注释。 阅读详情

相关推荐

Netty EventLoop与EventLoopGroup详解

Netty线程模型采用Reactor模式,通过EventLoop和EventLoopGroup实现高效I/O处理。核心设计包括:单线程串行化(一个Channel绑定一个EventLoop)、主从多线程模型(bossGroup处理连接,workerGroup处理I/O)、任务队列调度(ioRatio平衡I/O与任务执行)。EventLoop内部通过Selector轮询I/O事件,处理流程遵循I/O优先原则,支持定时任务和普通任务的有序执行。该模型通过线程亲和性避免锁竞争,配合轮询负载均衡策略实现高并发低延迟,

持续输出Java相关知识 1487

EventLoopGroup到底是个啥?

在Netty中,Channel为网络操作抽象类,EventLoop负责处理注册到其上的Channel处理I/O操作,两者配合参与I/O操作;EventLoopGroup是一个EventLoop的分组,它可以获取到一个或者多个EventLoop对象,因此它提供了迭代出EventLoop对象的方法。​ 在我们的使用示例中,使用到的就是: new Nio.

2830

[netty源码分析]--EventLoopGroup与EventLoop 分析netty的线程模型

netty核心类源码解析:分析netty的运行机制 EventLoopGroup与EventLoop解析:分析netty的线程模型 这一篇博文主要是从源码层次分析netty的线程模型。netty之所以是高性能NIO框架,其中主要贡献之一就是netty的线程模型的高性能,我们都知道netty的线程模型是基于Reactor线程模型,下面我们就来分析一下对于netty的reactor

惜暮 1万+

Netty之EventLoopGroup详解

Netty之EventLoopGroup详解EventLoopGroup EventLoopGroup netty是一款全异步,无阻塞的高性能框架,这篇文章着重讲了事件循环组的原理。 在之前,先讲一下netty的流程 netty是一款非阻塞框架,acceptor接收请求,poller起select的作用,像一个列车一样,把请求来回在acceptor和线程池之间传递,因为如果没有poller,就不...

zaltan_cgw的博客 6535

Netty 核心源码解读 —— EventLoop 篇

SingleThreadEventExecutor 实现了在 Netty 中对本地线程的抽象,在 SingleThreadEventExecutor 类中封装了一个 Thread thread 属性,也正因此,我们常说一个 NioEventLoop 其实是与一个线程绑定。在 NioEventLoop 中,NioEventLoop.run() 执行了与 Channel 相关的 IO 操作,包括调用 select 等待就绪的 IO 事件、读写数据与数据的处理等。doStartThread 是在。

2401_87195671的博客 485

Netty 4源码解析:服务端启动

Netty 4源码解析:服务端启动1.基础知识1.1 Netty 4示例因为Netty 5还处于测试版,所以选择了目前比较稳定的Netty 4作为学习对象。而且5.0的变化也不像4.0这么大,好多网上的例子都已经过时了。 <dependency> <groupId>io.netty</groupId> <artifactId>netty-

西代零零发 1万+

Netty源码解析之线程池的实现(一):EventLoopGroup和EventLoop

Netty中的线程池实现方式和JDK完成不同。Netty中的线程池准确的说可以叫做执行器组,即EventLoopGroup,执行器组EventLoopGroup里面包含若干个执行器EventLoop。这种包含关系,以我们惯常的编码方式来实现的话,肯定是在EventLoopGroup中使用一个集合属性(如栈、链表等)来存储EventLoop。

weixin_43274704的博客 1377

面试题趣谈:Netty中的EventLoopGroup的作用是什么的?实现原理是什么?

能否解释一下Netty中的EventLoopGroup是做什么的?它的实现原理是什么?EventLoopGroup在Netty中非常关键,它本质上是一个线程池,用于获取线程并管理线程的生命周期。首先,EventLoopGroup默认会创建CPU核心数*2 个线程,也就是会利用多核CPU。最小会有一个线程,这通过ThreadPerTaskExecutor线程池实现。然后,每个线程都对应一个EventExecutor,组成一个EventExecutor数组。线程和EventExecutor一一对应。

Gemini的博客 275

Netty组件EventLoopGroup和EventLoop源码分析

既然选择这个行业,选择了做一个程序员,也就明白只有不断学习,积累实战经验才有资格往上走,拿高薪,为自己,为父母,为以后的家能有一定的经济保障。学习时间都是自己挤出来的,短时间或许很难看到效果,一旦坚持下来了,必然会有所改变。不如好好想想自己为什么想进入这个行业,给自己内心一个答案。面试大厂,最重要的就是夯实的基础,不然面试官随便一问你就凉了;其次会问一些技术原理,还会看你对知识掌握的广度,最重要的还是你的思路,这是面试官比较看重的。

m0_55030688的博客 847

从零开始:在Ubuntu 22.04上配置Isaac Gym Preview 3环境(含常见错误解决方案)

本文提供了在Ubuntu 22.04系统上从零开始配置Isaac Gym Preview 3环境的完整实战指南。内容涵盖NVIDIA驱动安装、Conda环境搭建、CUDA与PyTorch版本精准匹配、Isaac Gym核心安装与验证,并重点介绍了针对四足机器人等复杂系统的强化学习训练环境配置、常见错误解决方案及性能调优技巧,旨在帮助开发者高效部署这一高性能物理仿真平台。

weixin_29048775的博客 400

Ollama内网离线部署大模型实战:从模型文件到私有化服务

本文详细介绍了如何在内网离线环境下,利用Ollama部署私有化大模型服务。内容涵盖从获取GGUF格式模型文件、手动安装Ollama、编写核心Modelfile配置文件,到创建运行模型、性能调优及安全加固的全流程实战指南,旨在帮助企业安全、可控地构建内部AI能力。

weixin_29209805的博客 233

EventLoop和EventLoopGroup

EventLoop和EventLoopGroup描述了Netty程序运行所使用的线程模型,通过修改EventLoopGroup,可以让Netty在不同的线程模型间快速切换,甚至可以在Nio和Bio间一键切换。 ​ 1. EventLoopGroup EventLoopGroup直译过来叫「事件循环组」,它管理着一组EventLoop。 EventLoopGroup实现了Iterable接口,可以通过迭代器遍历它管理的EventLoop。 ​ EventLoopGroup还继承了ScheduledExecu

程序员小潘 1683

无监督学习初探:K-Means聚类与主成分分析(PCA)

K-Means适用于快速分组,但对数据分布敏感,可结合轮廓系数评估质量。PCA通过特征值分解实现线性降维,需注意非线性场景的替代方案(如UMAP)。进阶方向:聚类:谱聚类、高斯混合模型(GMM)处理复杂形状。降维:t-SNE、自编码器处理非线性结构。

weixin_69882801的博客 1459

Netty源码解析-EventLoop与EventLoopGroup初探

前言: 在之前的ServerBootstrap示例中,有两句代码比较独特 NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(DEFAULT_EVENT_LOOP_THREADS); 通过其实现接口EventLoopGroup的注解我们了解到, /** * Special {@link EventExec...

恐龙弟旺仔的博客 898

多尺度Transformer+特征融合新范式,算力减半精度猛增

在大模型时代,多尺度特征融合与Transformer架构的结合正成为研究热点。多尺度特征融合能够捕捉数据在不同尺度上的关键信息,而Transformer架构凭借其强大的并行处理能力和对长距离依赖的建模能力,为复杂数据处理提供了新的思路。这种结合在处理多模态数据时展现出巨大潜力。

Tulingxueshu的博客 1070

【科技前沿】用深度强化学习优化电网,让电力调度更聪明!

Hey小伙伴们,今天我要跟大家分享一个超级酷炫的技术应用——深度强化学习在电网优化中的典型案例!如果你对机器学习感兴趣,或是正寻找如何用AI技术解决实际问题的方法,这篇分享绝对不容错过!👩‍💻✨

Jacklx888的博客 3260

EventloopGroup 和 EventLoop了解么?他们两者的关系是什么?

作者简介:大家好,我是码炫码哥,前中兴通讯、美团架构师,现任某互联网公司CTO,兼职码炫课堂主讲源码系列专题代表作:《jdk源码&多线程&高并发》,《深入tomcat源码解析》,《深入netty源码解析》,《深入dubbo源码解析》,《深入springboot源码解析》,《深入spring源码解析》,《深入redis源码解析》等联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬。

smart_an的专栏 773

字节跳动消息队列深度剖析:从BMQ架构到重复消费实战

消息队列作为分布式系统的核心基础设施,承担着解耦、异步、削峰填谷的关键职责。从Kafka到自研BMQ,字节跳动通过存储计算分离架构与EC纠删码技术解决了海量数据下的存储成本与扩展性难题。深入理解Topic、Partition、Consumer Group与Offset机制,是掌握消息队列原理的基础。消息重复消费无法完全避免,需通过幂等设计、手动提交Offset等手段兜底。同时,从嵌入式FreeRTOS消息队列到分布式消息中间件,生产者-消费者模型一脉相承。本文结合字节跳动内部实践,剖析消息队列架构演进、重复

weixin_29061509的博客 234

Netty:Netty中的EventLoop和EventLoopGroup

本文转自博客园-学无止境《netty中的EventLoop和EventLoopGroup》 一、Netty的线程模型   在讨论Netty线程模型时候,一般首先会想到的是经典的Reactor线程模型,尽管不同的NIO框架对应Reactor模式的实现存在差异,但本质上还是遵循了Reactor的基础线程模型。 Reactor的3中线程模型: Reactor单线程模型 Reactor多线程模型 主从Reactor多线程模型 Netty的线程模型并不是一成不变的,实际通过用户的启动配置参数来配置。 在创建Se.

我是nlefer,想做一个有温度、有情怀的人 870

Amber分子动力学模拟:蛋白结构准备全流程与关键注意事项

分子动力学模拟是研究蛋白结构、配体结合与构象变化的重要计算手段,其结果的可靠性高度依赖初始结构的质量。在Amber模拟体系中,结构准备是决定后续计算成败的“一票否决”环节,任何缺失残基、错误质子化状态或未处理的二硫键都可能让长时程模拟失去意义。从PDB原始文件出发,需依次完成结构检查与清洗、残基命名统一、配体参数化、金属离子建模、加氢及质子化状态判断,最后通过tleap构建力场、溶剂盒子与离子环境。这一过程看似琐碎,却直接决定了蛋白在模拟中的物理合理性。无论是解析催化机制、评估药物结合亲和力,还是探索构象变

weixin_31714129的博客 254

成功解决raise Py4JError py4j.protocol.Py4JError: py4j.protocol.Py4JError: Could not find py4j jar at 

成功解决raise Py4JError("Could not find py4j jar at {0}".format(jarpath)) py4j.protocol.Py4JError: Could not find py4j jar at 目录 解决问题 解决思路 解决方法 1、第一步安装jdk 2、第二步安装或升级py4j 解决问题 raise Py4JError("Could not find py4j jar at {0...

头部AI社区如有邀博主AI主题演讲请私信—心比天高,仗剑走天涯,保持热爱,奔赴向梦想!低调,专注,谦虚,自律,反思,成长,还算比较正能量的博主,公益免费传播…内心特别想在AI界做出一些可以推进历史进程影响力的技术(兴趣使然,有点小情怀,也有点使命感呀 4634

netty5.x源码分析-EventLoopGroup和EventLoop

EventLoopGroup和EventLoop的创建 EventLoopGroup构造方法参数有两个一个是线程数一个是executor 如果不给线程数默认先读取系统变量io.netty.eventLoopThreads对应的值,如果没有则取cpu核数*2个 如果executor不给定则默认...

311

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

深入剖析Netty之EventLoop刨根问底

在我们的日常使用中,EventLoopGroup是我们的老朋友了,EventLoopGroup我们已经讲解过了,那EventLoop是个啥呢?主要是用来做什么的?今天我就来带大家一探究竟!

785

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

【Netty源码解读和权威指南】第20篇:Netty EventLoop源码解析(下)—— NioEventLoopGroup内幕

本文摘要:Netty EventLoopGroup源码解析(下)—— NioEventLoopGroup内幕 本文深入解析Netty NioEventLoopGroup的实现原理,通过电商平台真实案例(配置不当导致性能下降56%)揭示合理配置线程数的重要性。文章系统讲解了EventLoopGroup的设计哲学、核心功能及与传统线程池的区别,详细分析了其继承体系与核心API,包括5种创建方式(默认配置、指定线程数、自定义线程工厂等)。通过ASCII图示对比传统线程池与Netty线程模型的差异,强调EventL

xyghehehehe的专栏 259

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Netty源码深度解析:从启动到数据流转的全链路剖析

本文深入解析Netty 4.1.x核心源码,揭示其高性能网络编程的实现原理。主要内容包括:1.启动流程分析:详细拆解ServerBootstrap初始化、Channel注册及端口绑定过程,展现主从Reactor模型的实现;2.线程模型剖析:深入EventLoop工作机制,包括事件循环、任务队列及JDK空轮询修复等关键技术;3.数据读写全链路:从客户端发送到服务端处理的完整流程,涵盖粘包拆包、编解码等核心环节;4.设计模式应用:责任链模式在ChannelPipeline中的实现,以及事件驱动模型的异步处理机制

weixin_38436441的博客 1091
上一篇: Netty源码解析(三)之客户端的连接
下一篇: Netty源码解析(五)之ByteBuf
枫_Maple
博客等级 码龄9年 37粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值