即使业务逻辑是纯CPU操作,是否也需要在channelread方法中开启一个新的线程来执行业务逻辑?

Is it necessary to start a new thread in the channelread method to execute the business logic even if business logic is a pure CPU operation?

我看到如下代码(基于netty的服务器):

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // Release IO thread
        AllChannelHandler.channelRead(() -> {
            // business logic...
            // response
            ctx.channel().writeAndFlush(new Object());
        });
    }
    // other code

}

这是AllChannelHandler#channelRead:

public class AllChannelHandler {

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8, 1, TimeUnit.MINUTES,
            new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());


    public static void channelRead(Runnable r) {
        executor.execute(r);
    }

}

如果业务逻辑是一个IO操作,那么新开一个线程来做这个操作就很容易理解了。

但我想知道即使业务逻辑是纯CPU操作,是否有必要在channelread方法中启动一个新线程来执行业务逻辑?

如果您的业务逻辑正在执行阻塞 IO,那么您必须在另一个线程中执行它以避免阻塞事件循环。

但是如果你有一个非阻塞的API(比如当IO操作是基于NIO的时候),你不必阻塞线程并且你不需要一个新的线程——你需要继续。

我在这里解释了如何在 Netty 中完成此操作:

顺便说一句,对于阻塞代码,netty 还提供了一个更简洁的解决方案,如下所述:https://netty.io/4.1/api/io/netty/channel/ChannelPipeline.html (查找“构建管道”)