EventLoop

在之前介绍Bootstrap的初始化以及启动过程时,我们多次接触了NioEventLoopGroup这个类,关于这个类的理解,还需要了解netty的线程模型。NioEventLoopGroup可以理解为一组线程,这些线程每一个都可以独立地处理多个channel产生的io事件。

NioEventLoopGroup初始化

我们看其中一个参数比较多的构造方法,其他一些参数较少的构造方法使用了一些默认值,使用的默认参数如下:

  • SelectorProvider类型,用于创建socket通道,udp通道,创建Selector对象等,默认值是SelectorProvider.provider(),大部分情况下使用默认值就行,这个方法最终创建的是一个WindowsSelectorProvider对象
  • SelectStrategyFactory,Select策略类的工厂类,它的默认值是DefaultSelectStrategyFactory.INSTANCE,就是一个SelectStrategyFactory对象本身,而SelectStrategyFactory工厂产生的是DefaultSelectStrategy策略类。
  • RejectedExecutionHandler,拒绝任务的策略类,决定在任务队列已满时采取什么样的策略,类似于jdk线程池的RejectedExecutionHandler的作用

接下来,我们看一下其中的一个常用的构造方法,

  1. public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory,
  2. final SelectorProvider selectorProvider, final SelectStrategyFactory selectStrategyFactory) {
  3. super(nThreads, threadFactory, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
  4. }

可见,当前类中并没有什么初始化逻辑,直接调用了父类的构造方法,所以我们接着看父类MultithreadEventLoopGroup的构造方法:

  1. protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
  2. super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args);
  3. }

同样,并未做任务处理,直接调用父类构造方法,所以我们接着看MultithreadEventExecutorGroup构造方法,初始化逻辑的实现在这个类中,

MultithreadEventExecutorGroup构造方法

通过上一小结的分析,我们知道NioEventLoopGroup的构造方法的主要逻辑的实现是在MultithreadEventExecutorGroup类中,并且在调用构造方法的过程中加上了一个参数的默认值,即EventExecutorChooserFactory类型参数的默认值DefaultEventExecutorChooserFactory.INSTANCE,这个类以轮询(roundrobin)的方式从多个线程中依次选出线程用于注册channel。

总结一下这段代码的主要步骤:

  • 首先是一些变量的非空检查和合法性检查

  • 然后根据传入的线程数量,创建若干个子执行器,每个执行器对应一个线程

  • 最后以子执行器数组为参数,使用选择器工厂类创建一个选择器

  • 最后给每个子执行器添加一个监听器,以监听子执行器的终止,做一些簿记工作,使得在所有子执行器全部终止后将当前的执行器组终止

    protected MultithreadEventExecutorGroup(int nThreads, Executor executor,

    EventExecutorChooserFactory chooserFactory, Object... args) {

    // 首先是变量的非空检查以及合法性判断,

    // nThreads在MultithreadEventLoopGroup的构造方法中已经经过一些默认值处理,

    if (nThreads <= 0) {

    throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));

    }

    1. // 这里一般都会使用默认值,
    2. // ThreadPerTaskExecutor的作用即字面意思,一个任务一个线程
    3. if (executor == null) {
    4. executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
    5. }
    6. // 子执行器的数组,一个子执行器对应一个线程
    7. children = new EventExecutor[nThreads];
    8. // 根据传入的线程数量创建多个自执行器
    9. // 注意,这里子执行器创建好后并不会立即运行起来
    10. for (int i = 0; i < nThreads; i ++) {
    11. boolean success = false;
    12. try {
    13. children[i] = newChild(executor, args);
    14. success = true;
    15. } catch (Exception e) {
    16. // TODO: Think about if this is a good exception type
    17. throw new IllegalStateException("failed to create a child event loop", e);
    18. } finally {
    19. // 如果创建子执行器不成功,那么需要将已经创建好的子执行器也全部销毁
    20. if (!success) {
    21. for (int j = 0; j < i; j ++) {
    22. children[j].shutdownGracefully();
    23. }
    24. // 等待所以子执行器停止后在退出
    25. for (int j = 0; j < i; j ++) {
    26. EventExecutor e = children[j];
    27. try {
    28. while (!e.isTerminated()) {
    29. e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
    30. }
    31. } catch (InterruptedException interrupted) {
    32. // Let the caller handle the interruption.
    33. Thread.currentThread().interrupt();
    34. break;
    35. }
    36. }
    37. }
    38. }
    39. }
    40. // 创建一个子执行器的选择器,选择器的作用是从子执行器中选出一个
    41. // 默认使用roundRobin的方式
    42. chooser = chooserFactory.newChooser(children);
    43. final FutureListener<Object> terminationListener = new FutureListener<Object>() {
    44. @Override
    45. public void operationComplete(Future<Object> future) throws Exception {
    46. if (terminatedChildren.incrementAndGet() == children.length) {
    47. terminationFuture.setSuccess(null);
    48. }
    49. }
    50. };
    51. // 给每个子执行器添加监听器,在子执行器终止的时候做一些工作
    52. // 每有一个子执行器终止时就将terminatedChildren变量加一
    53. // 当所有子执行器全部终止时,当前这个执行器组就终止了
    54. for (EventExecutor e: children) {
    55. e.terminationFuture().addListener(terminationListener);
    56. }
    57. // 包装一个不可变的集合
    58. Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
    59. Collections.addAll(childrenSet, children);
    60. readonlyChildren = Collections.unmodifiableSet(childrenSet);

    }

NioEventLoopGroup.newChild

上面的方法中调用了newChild方法来创建一个子执行器,而这个方法是一个抽象方法,我们看NioEventLoopGroup类的实现:

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

可见仅仅是简单地创建了一个NioEventLoop对象。

小结

到这里,我们就把NioEventLoopGroup的初始化过程分析完了。我们不禁思考,既然NioEventLoopGroup是一个执行器组,说白了就是一组线程,那这些线程是什么时候跑起来的呢?如果读者还有印象,应该能记得我们在分析Bootstrap建立连接过程时,channel初始化之后需要注册到EventLoopGroup中,其实是注册到其中的一个EventLoop上,注册逻辑最终是在AbstractChannel.AbstractUnsafe.register方法中实现的,其中有一段代码:

  1. if (eventLoop.inEventLoop()) {
  2. register0(promise);
  3. } else {
  4. try {
  5. eventLoop.execute(new Runnable() {
  6. @Override
  7. public void run() {
  8. register0(promise);
  9. }
  10. });
  11. } catch (Throwable t) {
  12. logger.warn(
  13. "Force-closing a channel whose registration task was not accepted by an event loop: {}",
  14. AbstractChannel.this, t);
  15. closeForcibly();
  16. closeFuture.setClosed();
  17. safeSetFailure(promise, t);
  18. }
  19. }

首先调用eventLoop.inEventLoop()判断执行器的线程与当前线程是否是同一个,如果是则直接执行注册的代码,如果不是就调用eventLoop.execute将注册逻辑封装成一个任务放到执行器的任务队列中,接下里我们就以这个方法为切入点,探究一下子执行器线程的启动过程。

AbstractEventExecutor.inEventLoop

首先,让我们来看一下这个方法,这个方法的作用是判断当前线程与执行器的线程是否同一个线程。

  1. public boolean inEventLoop() {
  2. return inEventLoop(Thread.currentThread());
  3. }

SingleThreadEventExecutor.inEventLoop

代码很简单,就不多说了。

public boolean inEventLoop(Thread thread) {

return thread == this.thread;

}

SingleThreadEventExecutor.execute

方法很简单,核心逻辑在startThread方法中,

  1. public void execute(Runnable task) {
  2. // 非空检查
  3. if (task == null) {
  4. throw new NullPointerException("task");
  5. }
  6. // 执行到这里一般都是外部调用者,
  7. boolean inEventLoop = inEventLoop();
  8. // 向任务队列中添加一个任务
  9. addTask(task);
  10. // 如果当前线程不是执行器的线程,那么需要检查执行器线程是否已经运行,
  11. // 如果还没在运行,就需要启动线程
  12. if (!inEventLoop) {
  13. startThread();
  14. // 检查线程是否被关闭
  15. if (isShutdown()) {
  16. boolean reject = false;
  17. try {
  18. // 将刚刚添加的任务移除
  19. if (removeTask(task)) {
  20. reject = true;
  21. }
  22. } catch (UnsupportedOperationException e) {
  23. // The task queue does not support removal so the best thing we can do is to just move on and
  24. // hope we will be able to pick-up the task before its completely terminated.
  25. // In worst case we will log on termination.
  26. }
  27. if (reject) {
  28. reject();
  29. }
  30. }
  31. }
  32. // addTaskWakesUp不知道这个变量意义是什么,NioEventLoop传进来的是false
  33. // 向任务队列中添加一个空任务,这样就能够唤醒阻塞的执行器线程
  34. // 有些情况下执行器线程会阻塞在taskQueue上,
  35. // 所以向阻塞队列中添加一个元素能够唤醒哪些因为队列空而被阻塞的线程
  36. if (!addTaskWakesUp && wakesUpForTask(task)) {
  37. wakeup(inEventLoop);
  38. }
  39. }

SingleThreadEventExecutor.startThread

这个方法的主要作用是维护内部的状态量state,使用cas指令并发情况下对状态量的修改是线程安全的,并且对于状态量的判断保证启动逻辑只被执行一次

  1. private void startThread() {
  2. // 状态量的维护
  3. if (state == ST_NOT_STARTED) {
  4. // 这里使用了jdk中的原子更新器AtomicIntegerFieldUpdater类,
  5. // 使用cpu的cas指令保证并发情况下能够安全地维护状态量
  6. // 保证只有一个线程能够执行启动逻辑,保证启动逻辑只被执行一次
  7. if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_STARTED)) {
  8. boolean success = false;
  9. try {
  10. // 实际启动线程的逻辑
  11. doStartThread();
  12. success = true;
  13. } finally {
  14. if (!success) {
  15. STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_NOT_STARTED);
  16. }
  17. }
  18. }
  19. }
  20. }

SingleThreadEventExecutor.doStartThread

这个方法我就不贴代码了,说一下它的主要作用:

  • 使用内部的Executor对象(一般是一个ThreadPerTaskExecutor)启动一个线程,并执行任务
  • 维护执行器的运行状态,主要是通过内部的状态量和cas指令来保证线程安全;此外维护内部的一些簿记量,例如线程本身的引用,线程启动时间等
  • 线程结束时做一些收尾和清理工作,例如将剩余的任务跑完,运行关闭钩子,关闭底层的selector(这个是具体的子类的清理逻辑),同时更新状态量

具体的业务逻辑仍然是在子类中实现的,也就是SingleThreadEventExecutor.run()方法的具体实现。

NioEventLoop.run

我们仍然以NioEventLoop为例,看一下它实现的run方法。还大概讲一下它的主要逻辑:

  • 首选这个方法是一个循环,不断地通过调用jdk底层的selector接收io事件,并对不同的io事件做处理,同时也会处理任务队列中的任务,以及定时调度或延迟调度的任务
  • 调用jdk的api, selector接收io事件
  • 处理各种类型的io事件
  • 处理任务

这里,我就不贴代码了,其中比较重要的是对一些并发情况的考虑和处理,如selector的唤醒时机。接下来,主要看一下对于各种io事件的处理,至于任务队列以及调度队列中任务的处理比较简单,就不展开了。

NioEventLoop.processSelectedKeysOptimized

这个方法会遍历所有接受到的io事件对应的selectionKey,然后依次处理。

  1. private void processSelectedKeysOptimized() {
  2. // 遍历所有的io事件的SelectionKey
  3. for (int i = 0; i < selectedKeys.size; ++i) {
  4. final SelectionKey k = selectedKeys.keys[i];
  5. // null out entry in the array to allow to have it GC'ed once the Channel close
  6. // See https://github.com/netty/netty/issues/2363
  7. selectedKeys.keys[i] = null;
  8. final Object a = k.attachment();
  9. if (a instanceof AbstractNioChannel) {
  10. // 处理事件
  11. processSelectedKey(k, (AbstractNioChannel) a);
  12. } else {
  13. @SuppressWarnings("unchecked")
  14. NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
  15. processSelectedKey(k, task);
  16. }
  17. // 如果需要重新select,那么把后面的selectionKey全部置0,然后再次调用selectNow方法
  18. if (needsToSelectAgain) {
  19. // null out entries in the array to allow to have it GC'ed once the Channel close
  20. // See https://github.com/netty/netty/issues/2363
  21. selectedKeys.reset(i + 1);
  22. selectAgain();
  23. i = -1;
  24. }
  25. }
  26. }

NioEventLoop.processSelectedKey

这个方法首先对SelectionKey无效的情况做了处理,分为两种情况:channel本身无效了;channel仍然是正常的,只不过是被从当前的selector上注销了,可能在其他的selector中仍然是正常运行的

  • 对于第一种情况,需要关闭channel,即关闭底层的连接
  • 对于第二种情况则不需要做任何处理。

接下来,我们着重分析一下对于四种事件的处理逻辑。

  1. private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
  2. final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe();
  3. // 如果selectionKey是无效的,那么说明相应的channel是无效的,此时需要关闭这个channel
  4. if (!k.isValid()) {
  5. final EventLoop eventLoop;
  6. try {
  7. eventLoop = ch.eventLoop();
  8. } catch (Throwable ignored) {
  9. // If the channel implementation throws an exception because there is no event loop, we ignore this
  10. // because we are only trying to determine if ch is registered to this event loop and thus has authority
  11. // to close ch.
  12. return;
  13. }
  14. // Only close ch if ch is still registered to this EventLoop. ch could have deregistered from the event loop
  15. // and thus the SelectionKey could be cancelled as part of the deregistration process, but the channel is
  16. // still healthy and should not be closed.
  17. // See https://github.com/netty/netty/issues/5125
  18. // 只关闭注册在当前EventLoop上的channel,
  19. // 理论上来说,一个channel是可以注册到多个Eventloop上的,
  20. // SelectionKey无效可能是因为channel从当前EventLoop上注销了,
  21. // 但是channel本身依然是正常的,并且注册在其他的EventLoop中
  22. if (eventLoop != this || eventLoop == null) {
  23. return;
  24. }
  25. // close the channel if the key is not valid anymore
  26. // 到这里说明channel已经无效了,关闭它
  27. unsafe.close(unsafe.voidPromise());
  28. return;
  29. }
  30. // 下面处理正常情况
  31. try {
  32. // 准备好的io事件
  33. int readyOps = k.readyOps();
  34. // We first need to call finishConnect() before try to trigger a read(...) or write(...) as otherwise
  35. // the NIO JDK channel implementation may throw a NotYetConnectedException.
  36. // 处理connect事件
  37. if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
  38. // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
  39. // See https://github.com/netty/netty/issues/924
  40. int ops = k.interestOps();
  41. ops &= ~SelectionKey.OP_CONNECT;
  42. k.interestOps(ops);
  43. unsafe.finishConnect();
  44. }
  45. // Process OP_WRITE first as we may be able to write some queued buffers and so free memory.
  46. // 处理write事件
  47. if ((readyOps & SelectionKey.OP_WRITE) != 0) {
  48. // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
  49. ch.unsafe().forceFlush();
  50. }
  51. // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
  52. // to a spin loop
  53. // 处理read和accept事件
  54. if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
  55. unsafe.read();
  56. }
  57. } catch (CancelledKeyException ignored) {
  58. unsafe.close(unsafe.voidPromise());
  59. }
  60. }

connect事件处理

从代码中可以看出,connect事件的处理时通过调用NioUnsafe.finishConnect完成的,我们看一下AbstractNioUnsafe.finishConnect的实现:

  1. public final void finishConnect() {
  2. // Note this method is invoked by the event loop only if the connection attempt was
  3. // neither cancelled nor timed out.
  4. assert eventLoop().inEventLoop();
  5. try {
  6. // 是否已经处于连接成功的状态
  7. boolean wasActive = isActive();
  8. // 抽象方法,有子类实现
  9. doFinishConnect();
  10. // 处理future对象,将其标记为成功
  11. fulfillConnectPromise(connectPromise, wasActive);
  12. } catch (Throwable t) {
  13. fulfillConnectPromise(connectPromise, annotateConnectException(t, requestedRemoteAddress));
  14. } finally {
  15. // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is used
  16. // See https://github.com/netty/netty/issues/1770
  17. if (connectTimeoutFuture != null) {
  18. connectTimeoutFuture.cancel(false);
  19. }
  20. connectPromise = null;
  21. }
  22. }

可以看出,主要是通过调用doFinishConnect实现完成连接的逻辑,具体到子类中,NioSocketChannel.doFinishConnect的实现是:

  1. protected void doFinishConnect() throws Exception {
  2. if (!javaChannel().finishConnect()) {
  3. throw new Error();
  4. }
  5. }

write事件处理

对于的write事件的处理时通过调用NioUnsafe.forceFlush方法完成,最终的实现在AbstractChannel.AbstractUnsafe.flush0中:

大体上看,这个方法的逻辑比较简单,但是实际上最复杂也是最核心的写入逻辑在子类实现的doWrite方法中。由于本篇的重点在于把NioEventLoop的主干逻辑梳理一下,所以这里不再继续展开,后面会单独来分析这一块的源码,这里涉及到netty中对缓冲区的封装,其中涉及到一些比较复杂的逻辑。

  1. protected void flush0() {
  2. // 如果正在写数据,直接返回
  3. if (inFlush0) {
  4. // Avoid re-entrance
  5. return;
  6. }
  7. // 输出的缓冲区
  8. final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
  9. if (outboundBuffer == null || outboundBuffer.isEmpty()) {
  10. return;
  11. }
  12. inFlush0 = true;
  13. // Mark all pending write requests as failure if the channel is inactive.
  14. if (!isActive()) {
  15. try {
  16. if (isOpen()) {
  17. outboundBuffer.failFlushed(new NotYetConnectedException(), true);
  18. } else {
  19. // Do not trigger channelWritabilityChanged because the channel is closed already.
  20. outboundBuffer.failFlushed(newClosedChannelException(initialCloseCause), false);
  21. }
  22. } finally {
  23. inFlush0 = false;
  24. }
  25. return;
  26. }
  27. try {
  28. // 将缓冲区的数据写入到channel中
  29. doWrite(outboundBuffer);
  30. } catch (Throwable t) {
  31. if (t instanceof IOException && config().isAutoClose()) {
  32. /**
  33. * Just call {@link #close(ChannelPromise, Throwable, boolean)} here which will take care of
  34. * failing all flushed messages and also ensure the actual close of the underlying transport
  35. * will happen before the promises are notified.
  36. *
  37. * This is needed as otherwise {@link #isActive()} , {@link #isOpen()} and {@link #isWritable()}
  38. * may still return {@code true} even if the channel should be closed as result of the exception.
  39. */
  40. initialCloseCause = t;
  41. close(voidPromise(), t, newClosedChannelException(t), false);
  42. } else {
  43. try {
  44. shutdownOutput(voidPromise(), t);
  45. } catch (Throwable t2) {
  46. initialCloseCause = t;
  47. close(voidPromise(), t2, newClosedChannelException(t), false);
  48. }
  49. }
  50. } finally {
  51. inFlush0 = false;
  52. }
  53. }

read事件和accept事件处理

乍看会比较奇怪,为什么这两个事件要放到一起处理呢,他们明明是不同的事件。这里主要还是考虑到编码的统一,因为read事件只有NioSocketChannel才会有,而accept事件只有NioServerSocketChannel才会有,所以这里通过抽象方法,让不同的子类去实现各自的逻辑,是的代码结构上更统一。我们这里看一下NioScketChannel的实现,而对于NioServerSocketChannel的实现我会在后续分析netty服务端的启动过程时在具体讲到,即ServerBootstrap的启动过程。

NioByteUnsafe.read

总结一下这个方法的主要逻辑:

  • 首先会获取缓冲分配器和相应的处理器RecvByteBufAllocator.Handle对象

  • 循环读取数据,每次分配一个一定大小(大小可配置)的缓冲,将channel中待读取的数据读取到缓冲中

  • 以装载有数据的缓冲为消息体,向channel的处理流水线(即pipeline)中触发一个读取的事件,让读取到的数据在流水线中传播,被各个处理器处理

  • 重复此过程,知道channel中没有可供读取的数据

  • 最后向pipeline中触发一个读取完成的事件

  • 最后还要根据最后一次读取到的数据量决定是否关闭通道,如果最后一次读取到的数据量小于0,说明对端已经关闭了输出,所以这里需要将输入关闭,即通道处于半关闭状态。

    1. public final void read() {
    2. final ChannelConfig config = config();
    3. // 如果通道已经关闭,那么就不需要再读取数据,直接返回
    4. if (shouldBreakReadReady(config)) {
    5. clearReadPending();
    6. return;
    7. }
    8. final ChannelPipeline pipeline = pipeline();
    9. // 缓冲分配器
    10. final ByteBufAllocator allocator = config.getAllocator();
    11. // 缓冲分配的处理器,处理缓冲分配,读取计数等
    12. final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle();
    13. allocHandle.reset(config);
    14. ByteBuf byteBuf = null;
    15. boolean close = false;
    16. try {
    17. do {
    18. // 分配一个缓冲
    19. byteBuf = allocHandle.allocate(allocator);
    20. // 将通道的数据读取到缓冲中
    21. allocHandle.lastBytesRead(doReadBytes(byteBuf));
    22. // 如果没有读取到数据,说明通道中没有待读取的数据了,
    23. if (allocHandle.lastBytesRead() <= 0) {
    24. // nothing was read. release the buffer.
    25. // 因为没读取到数据,所以应该释放缓冲
    26. byteBuf.release();
    27. byteBuf = null;
    28. // 如果读取到的数据量是负数,说明通道已经关闭了
    29. close = allocHandle.lastBytesRead() < 0;
    30. if (close) {
    31. // There is nothing left to read as we received an EOF.
    32. readPending = false;
    33. }
    34. break;
    35. }
    36. // 更新Handle内部的簿记量
    37. allocHandle.incMessagesRead(1);
    38. readPending = false;
    39. // 向channel的处理器流水线中触发一个事件,
    40. // 让取到的数据能够被流水线上的各个ChannelHandler处理
    41. pipeline.fireChannelRead(byteBuf);
    42. byteBuf = null;
    43. // 这里根据如下条件判断是否继续读:
    44. // 上一次读取到的数据量大于0,并且读取到的数据量等于分配的缓冲的最大容量,
    45. // 此时说明通道中还有待读取的数据
    46. } while (allocHandle.continueReading());
    47. // 读取完成
    48. allocHandle.readComplete();
    49. // 触发一个读取完成的事件
    50. pipeline.fireChannelReadComplete();
    51. if (close) {
    52. closeOnRead(pipeline);
    53. }
    54. } catch (Throwable t) {
    55. handleReadException(pipeline, byteBuf, t, close, allocHandle);
    56. } finally {
    57. // Check if there is a readPending which was not processed yet.
    58. // This could be for two reasons:
    59. // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
    60. // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
    61. //
    62. // See https://github.com/netty/netty/issues/2254
    63. // 这里isAutoRead默认是true, 所以正常情况下会继续监听read事件
    64. if (!readPending && !config.isAutoRead()) {
    65. removeReadOp();
    66. }
    67. }
    68. }
    69. }

总结

本篇主要分析了EventLoop的事件监听以及处理逻辑,此外处理处理io事件,也会处理添加进来的任务和定时调度任务和延迟调度任务。EventLoop就像是整个框架的发动机或者说是心脏,它通过jdk api进而简介地调用系统调用,不断地监听各种io事件,同时对不同的io事件分门别类采用不同的处理方式,对于read事件则会将网络io数据读取到缓冲中,并将读取到的数据传递给用户的处理器进行链式处理。Channelpipeline就像一个流水线一样,对触发的的各种事件进行处理。

遗留问题

  • NioSocketChannel.doWrite方法的写入逻辑的,待进一步分析
  • ChannelPipeline的详细分析,各种事件是怎么在处理器之间传播的,设计模式,代码结构等
  • 缓冲分配器和缓冲处理器的分析,它们是怎么对内存进行管理的,这也是netty高性能的原因之一。

netty中的发动机--EventLoop及其实现类NioEventLoop的源码分析的更多相关文章

  1. SqlAlchemy 中操作数据库时session和scoped_session的区别(源码分析)

    原生session: from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalch ...

  2. Django——基于类的视图源码分析 二

    源码分析 抽象类和常用视图(base.py) 这个文件包含视图的顶级抽象类(View),基于模板的工具类(TemplateResponseMixin),模板视图(TemplateView)和重定向视图 ...

  3. Arrays工具类使用与源码分析(1)

    Arrays工具类主要是方便数组操作的,学习好该类可以让我们在编程过程中轻松解决数组相关的问题,简化代码的开发. Arrays类有一个私有的构造函数,没有对外提供实例化的方法,因此无法实例化对象.因为 ...

  4. Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析

    目录 0.前言 1.TemporalAccessor源码 2.Temporal源码 3.TemporalAdjuster源码 4.ChronoLocalDate源码 5.LocalDate源码 6.总 ...

  5. Netty学习:ChannelHandler执行顺序详解,附源码分析

    近日学习Netty,在看书和实践的时候对于书上只言片语的那些话不是十分懂,导致尝试写例子的时候遭遇各种不顺,比如decoder和encoder还有HttpObjectAggregator的添加顺序,研 ...

  6. Django——基于类的视图源码分析 一

    基于类的视图(Class-based view)是Django 1.3引入的新的视图编写方式,用于取代以前基于函数(Function-based)方式. 借助于OO和Python中方便的多重继承特性, ...

  7. Django——基于类的视图源码分析 三

    列表类通用视图(list.py) 此文件包含用于显示数据列表常用的类和工具类.不仅可以方便的用于显示基于模型(Model)的数据列表,也可以用于显示自定义数据列表. 此图中绿色部分属于base.py, ...

  8. Disruptor中shutdown方法失效,及产生的不确定性源码分析

    版权声明:原创作品,谢绝转载!否则将追究法律责任. Disruptor框架是一个优秀的并发框架,利用RingBuffer中的预分配内存实现内存的可重复利用,降低了GC的频率. 具体关于Disrupto ...

  9. java String类 trim() 方法源码分析

    public String trim() {        int arg0 = this.value.length;   //得到此字符串的长度        int arg1 = 0;   //声 ...

随机推荐

  1. ajax的跨域请求问题:减少options请求

    服务器端在Response Headers里添加字段Access-Control-Max-Age: 86400 , "Access-Control-Max-Age"表明在86400 ...

  2. WPF中MVVM模式的 Event 处理

    WPF的有些UI元素有Command属性可以直接实现绑定,如Button 但是很多Event的触发如何绑定到ViewModel中的Command呢? 答案就是使用EventTrigger可以实现. 继 ...

  3. Android设备与外接U盘实现数据读取操作

    现在越来越多手机支持OTG功能,通过OTG可以实现与外接入的U盘等USB设备实现数据传输.关于OTG,可以参考: http://blog.csdn.net/srw11/article/details/ ...

  4. 开源 自由 java CMS - FreeCMS1.9 积分规则管理

    项目地址:http://www.freeteam.cn/ 积分规则管理 管理会员操作时积分处理规则. 1. 积分规则管理 从左側管理菜单点击积分规则进入. 2. 加入积分规则 在积分规则列表下方点击& ...

  5. 谷歌推出备份新工具:Google Drive将同步计算机文件

    Google 正在将云端硬盘 Drive 转变成更强大的文件备份工具.很快,Google Drive 将能监测并备份你电脑上的(几乎)所有文件,只要是你勾选的文档,Drive 就能同步至云端. 具体来 ...

  6. 好用的Markdown 编辑器及工具

    Markdown 是 2004 年由 John Gruberis 设计和开发的纯文本格式的语法,所以通过同一个名字它可以使用工具来转换成 HTML.readme 文件,在线论坛编写消息和快速创建富文本 ...

  7. iphone开发技巧整合

    1.NSCalendar用法 -(NSString *) getWeek:(NSDate *)d { NSCalendar *calendar = [[NSCalendar alloc] initWi ...

  8. mysql 视图,存储过程,游标,触发器,用户管理简单应用

    mysql视图——是一个虚拟的表,只包含使用时动态查询的数据 优点:重用sql语句,简化复杂的SQL操作,保护数据,可以给用户看到表的部分字段而不是全部,更改数据格式和表现形式 规则: 名称唯一,必须 ...

  9. WPF 数据模板的使用

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  10. entity framework 封装基类

    /// <summary> /// 查询业务基实现 /// </summary> /// <typeparam name="T"></ty ...