Skip to content

Why event loop uses more than one thread?

I always thought that asynchronous execution is about efficient resource utilization and thread safety, but today I ran into Netty’s strange behavior.

public class Example {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                        public void initChannel(SocketChannel channel) {
                                   .addLast(new ChannelOutboundHandlerAdapter() {
                                        public void read(ChannelHandlerContext ctx) {
                                            String id = String.valueOf(Thread.currentThread().getId());
                    .bind("localhost", 1234)
        } finally {

When I connected for the first time, I got 16. Then 17, 18, 19, etc. Every connection was executed on a new thread! Why? What’s the point of Netty, if it’s multi-threaded?



NioEventLoopGroup uses worker threads to utilize multiple CPU cores. As per the no-argument constructor javadoc:


Create a new instance using the default number of threads, the default ThreadFactory and the SelectorProvider which is returned by SelectorProvider.provider().

The deafult thread count as per MultithreadEventLoopGroup will be twice the number of available processors:

DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
            "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

Generally this should be enough to saturate the CPU without creating a huge number of threads. Spawn too few threads and you won’t get full CPU utilization. Spawn too many and you will waste substantial time context switching between them.

User contributions licensed under: CC BY-SA
10 People found this is helpful