跳至主要内容

Netty(3): EventLoop

Netty(3): EventLoop

We have discussed the Handler design in last blog: the InboundHandler & OutboundHandler, the handler & childHandler, the Servlet vs Handler. In this blog, we will dive into the thread pool abstraction in NettyEventLoop.

enter image description here

EventLoop Basic

From our previous code example, we can see that what we used are EventLoopGroup, which is a group of EventLoops, but what is EventLoop on earth?

Loop & Pool

The EventLoop, as its name indicates, is a infinite loop to handle IO events. A common implementation (NioEventLoop) is like following:

protected void run() {  
  for (;;) {  
    try {  
      switch (selectStrategy.calculateStrategy(selectNowSupplier, hasTasks())) {  
        case SelectStrategy.CONTINUE:  
          continue;  
        case SelectStrategy.SELECT:  
          select(wakenUp.getAndSet(false));  
  
          if (wakenUp.get()) {  
            selector.wakeup();  
          }  
        default:  
          // fallthrough  
       }  
  
      if (ioRatio == 100) {  
        try {  
          processSelectedKeys();  
        } finally {  
          // Ensure we always run tasks.  
          runAllTasks();  
        }  
      
        // ...
      }  
    } catch (Throwable t) {  
      handleLoopException(t);  
    }  
  }  
}

When processSelectedKeys, EventLoop may use different worker thread to run the tasks that IO event brings. So, EventLoop is also a thread pool.

In conclusion, EventLoop is

EventLoop = Event Dispatcher + Thread Pool (worker to handle IO events from `Channel`s)

Channel Registration

In order to have the functionality to do the Event Dispatch, Channel have to be registered in it, just like what we did in Java NIO:

servChannel.register(selector, SelectionKey.OP_ACCEPT);

And EventLoopGroup's comment proves it:

/**
  * Special  [`EventExecutorGroup`]  which allows registering  [`Channel`]s that get    
  * processed for later selection during the event loop.
  */
public interface EventLoopGroup extends EventExecutorGroup {
  ChannelFuture register(Channel channel);
}

Different Impliementations

Netty has many different ementations for EventLoop:

DefaultEventLoop, NioEventLoop, SingleThreadEventLoop, ThreadPerChannelEventLoop etc

SingleThreadEventLoop is the base class for DefaultEventLoop, NioEventLoop, ThreadPerChannelEventLoop, which run all task in a single thread.

ThreadPerChannelEventLoop is a implementation for OIO, where every Channel needs a thread. Today, we focus on NIO related (IO multiplex) implementations, which is more widely used.

NioEventLoop

NioEventLoop, which uses Java NIO as its underlying implementation, is actually a single thread pool. The coe concept in Java NIO is Channel, Selector, Buffer. We can find the usage of Channel and Buffer (although they are wrapped by Netty's class and we will clarify them later in this serial of blog).
And the functionality of Selector, which is the IO event dispatcher and choosing the right IO related code to execute is encapsulated in NioEventLoop as following code shows (notice that the real IO event handling is what Handler does, i.e. EventLoop will just call Handler).

private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {  
  try {  
    int readyOps = k.readyOps();  
    if ((readyOps & SelectionKey.OP_CONNECT) != 0) {  
      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());  
  }  
}

EpollEventLoop

If we work in Linux and want higher throughput, we can use EpollEventLoop. It is implemented by JNI, which will invoke the system call like epoll (it is only works on linux).

Compared with NioEventLoop, EpollEventLoop has following advantages:

  • It is edge-triggered, rather than level-triggered like NioEventLoop, which is more efficient as here said;
  • It is implemented by C, which means
    • It will cause less GC activity;
    • It needs less synchronized;
    • It can expose more Socket config option than using Java's Socket;

Thread Issue

When it comes to the Thread Pool and multiple thread coding, we need to be careful about the race conditions it may causes. So we need to find which thread will run the callback:

for a given connection, there can not be more than one wire runtime running ChannelsHandler code and functions back associates. In other words, within a ChannelPipeline, there is no need to worry about access competition issues, so we stay in this logic of not blocking the wires execution.

As the document specified, we don’t need to worry about the race condition if we don’t share variables using global variables. But this also require that our handler code not too time-consuming, otherwise the worker will be stuck and EventLoop can’t dispatch events.

This non-access competition relies on an event loop that reuses a small number of threads executions that never get stuck, which makes it possible to maximize performance by reducing switching times betweethreads of execution.

Ref

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (