The introduction

This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Today we’ll take a look at the classic IO pattern and how Netty is implemented.

Classic IO mode

  • BIO (blocking IO), prior to JDK1.4
  • NIO (non-blocking IO), jDK1.4
  • AIO (Asynchronous IO), JDK1.7

IO model features

  • Block: Read blocks if no data is passed, and write blocks when the buffer is full.
  • Non-blocking: Returns directly.
  • Synchronization: Who does the reading, if it’s done by the user process
  • Asynchronous: the user process is not required to read the data,

IO mode supported by Netty

Netty supports only NIO. BIO blocks synchronously, which causes the thread to block when it can’t get data. If a large number of requests come in, it has to wait, and the occupied system resources cannot be released.

For AIO, while Windows is mature, it cannot be used as a server, and AIO on Linux is not mature enough to provide significant performance improvements over NIO.

Netty’s various NIO implementations

Netty’s NIO was implemented by itself, and Netty thought it would be better to implement it itself:

  • Netty exposes more controllable parameters: NIO in the JDK defaults to horizontal triggering, while Netty defaults to edge triggering and horizontal triggering.
  • Netty implements better garbage collection performance

Advantages of BIO: The simple BIO code is suitable for scenarios with a small number of connections and low concurrency.

Netty a variety of IO mode switching resolution

Here, we directly enter the code. For server development, if you want to switch the IO mode, the first switch is EventLoopGroup, which is the corresponding development mode, and then switch the IO mode, which is the corresponding Channel.

Let’s click on the Channel method to see:

Above we preach here is NioServerSocketChannel. Class, and the formal parameter is a clazz objects, that is to say that we can preach BioServerSocketChannel. Class, also can pass the other Channel, Then we look at what happens in the method:

ReflectiveChannelFactory () {ReflectiveChannelFactory ();}

Here reflection calls the constructor of the object used to create the object:

The created object is then our NioServerSocketChannel instance, and this implementation is the generic plus reflection factory implementation pattern.