简体   繁体   中英

How Netty uses thread pools?

Can you please explain how Netty uses thread pools to work? Do I understand correctly, that there are two kinds of thread-pools: boss and worker. Boss ones are used to do I/O and worker are used to call user callbacks (messageReceived) to process data?

This is from NioServerSocketChannelFactory document

A ServerSocketChannelFactory which creates a server-side NIO-based ServerSocketChannel. It utilizes the non-blocking I/O mode which was introduced with NIO to serve many number of concurrent connections efficiently.

How threads work
There are two types of threads in a NioServerSocketChannelFactory; one is boss thread and the other is worker thread.

Boss threads
Each bound ServerSocketChannel has its own boss thread. For example, if you opened two server ports such as 80 and 443, you will have two boss threads. A boss thread accepts incoming connections until the port is unbound. Once a connection is accepted successfully, the boss thread passes the accepted Channel to one of the worker threads that the NioServerSocketChannelFactory manages.

Worker threads
One NioServerSocketChannelFactory can have one or more worker threads. A worker thread performs non-blocking read and write for one or more Channels in a non-blocking mode.

In Nio model, bossThread take care all bounded socket(listen socket), workerThread take care Accepted-socket (included IO and call event method such as messageReceived).

Description related to Netty Nio implementation (3.2.4.Final) NioServerSocketChannelFactory.

has to be able to deliver at least Number of Workers threads (currently default 2*number of cores). 必须至少能够提供Number of Workers线程(当前默认为2 *内核数)。

Why?

In case of this implementation each worker has his own selector loop, this means that each worker will "eat up" one thread to sleep on the selector. Also that worker (and associated thread) is responsible for doing all the actual writes and reads (including fireing events on the pipeline, that means handlers are executed in that workers thread).

thread pool, actually the thread pool is unneeded because current implementation acquires only a single thread from it. 线程池的 ,实际上线程池是不需要的,因为当前实现只从它获取单个线程。 That thread sleeps on the selector for server socket most of the time, after accepting connection that connection is registered with a worker. From that moment on worker is responsible for serving that connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM