跳至主要内容

Netty(1): Abstration

Netty(1): Abstration

As the one of the most widely used network library in Java, Netty has become the de facto standard of network communication in Java. In this blog, we learn some basic concept and designs of Netty by examples in their website.

The following is the template code to start a server:

EventLoopGroup group = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();  
try { 
  ServerBootstrap b = new ServerBootstrap(); 
  b.group(group, worker)  
      .channel(NioServerSocketChannel.class)  
      .handler(new xxxHandler())
      .childHandler(new yyyHandler());  
  b.bind(PORT).sync().channel().closeFuture().await();  
} finally {  
  worker.shutdownGracefully();
  group.shutdownGracefully();  
}

In the view of normal Java plain IO & Servlet developer, this code snippet can be very confusing.

In plain Java IO way, we bind, listen, accept through ServerSocket. Then we start a new thread/executor to handle the received socket connection. If we use Java NIO, things goes a little different: we use ServerSocketChannel to listen connection and Selector to arrange multiple channels.

When we do it using Java EE servlet(or Spring), the listening job is done by container and it will pass the request to servlet & filter etc to handle.

So, in order to understand the logic behind the code, we need to understand the design and abstractions of Netty.

Basic Abstraction

Netty adopts an event-driven style design, which means, in Netty, all network related things are abstracted as events, and we react by adding listener or call back.

Events

Netty split events into two general kinds: Inbound and Outbound. Outbound events is often triggered by our operations, like write, bind, connect. Inbound events, on the other hand, is usually generated by IO thread, like channelRegistered, being in connected state – channelActive, receiving some packet from remove peer – channelRead.

So, Netty has two corresponding kinds of handler to handle those two kinds of events: ChannelInboundHandler & ChannelOutboundHandler.

State

When received events, our server/client will be triggered to invoke handler, and we can use handler to get involved in state change.

Examples: Registered & Active

We have mentioned that some common events like channelRegistered, channelActive and channelRead. channelRead is very easy to understand, which means channel received some packet. But what the meaning of Registered & Active?

Registered state means the Bootstrap has a channel registered in the eventloop, which is somewhat similar concept compared with Java NIO's selector .

Active is a little different. It is a new idea introduced in Netty 4, which is merged from channelOpen, channelBound, and channelConnected. Of course, channelDisconnected, channelUnbound, and channelClosed have been merged to channelInactive. Likewise, Channel.isBound() and isConnected() have been merged to isActive().

This merge is because Netty thought simple Open or Bound state is not so useful, and the final Connected state is when user will be interested in.

So the state transfer when bootstrap is like following:

  • server: channelRegistered -> bind (out bound) -> channelActive
  • client: channelRegistered -> connect (out bound) -> channelActive

What should be noticed is that channelRegistered and channelUnregistered are not equivalent to channelOpen and channelClosed. They are new states introduced to support dynamic registration, deregistration, and re-registration of a Channel.

Pipeline & Handler

In order to let user get involved in the state change and react to corresponding event, Netty has a chain of handlers which is called Pipeline. In order to decouple multiple handlers, handler not invoke each other: they are invoked through ChannelHandlerContext object. By calling fireXXX, user can trigger specific kinds of event for upcoming handler to react, make state change very flexible.

public class MyInboundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Connected!");
        ctx.fireChannelActive(); // or fire other events
    }
}

EventLoop: Thread Pools

We have the code (in handler) to handle event and state, now we need thread to run them. Because those worker thread run in a loop to handle event, it is named as EventLoop.

If different worker threads run different kinds of jobs, like different code, different running time, they will have some performance penalty: some hot code which should be compiled into native code, may not benefit from this JIT functionality; when switching between long-lived job and short-lived job, CPU cache will be flushed; the number of thread in pool will be hard to control and init.

So, Netty use different threads to handle different jobs:

  • A EventLoop for receiving remote connection, do the long-lived accept job;
  • A EventLoop to run pipeline, which is relative short job;

Conclusion

In this blog, we learned some basic concepts and abstractions in Netty. Through this way, we understand how Netty view network related events and some design decision under the hood.

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 << (