Eduardo Bezerra
Eduardo Bezerra

Reputation: 1963

How to configure Netty to have a single worker thread?

Let's assume that we're implementing a service that accesses some shared data, and that there is no way of partitioning those data into portions that can be accessed independently. For this reason, not more than one single thread can read/write those data at any given time.

A correct, although inefficient way to solve this is to just use some synchronization technique (Semaphores, Monitors etc.), so that the Netty worker threads don't corrupt the shared data by accessing it at the same time (when servicing requests). However, the whole locking/unlocking would certainly degrade performance by a huge amount.

So, the first question is:

How to configure Netty to have a single worker thread?

And the second is:

What could be a good design to solve the problem of having a shared data whose access cannot be done by more than 1 thread at any given time?

The 1-worker solution seems to solve the problem, but I wonder how that would hurt Netty's performance, since there might be tens of thousands of clients connected at the same time, sending requests and waiting for the replies...

Upvotes: 0

Views: 513

Answers (2)

Tatiana Goretskaya
Tatiana Goretskaya

Reputation: 576

Just a code sample for @forty-two's 2nd option:

private final StringDecoder DECODER = new StringDecoder();
private final ByteArrayEncoder ENCODER = new ByteArrayEncoder();
private final CustomBusinessHandler SERVER_HANDLER = new CustomBusinessHandler ();

...

ServerBootstrap b = new ServerBootstrap();
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(1);
b.group(bossGroup, workerGroup).childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();                     
        // the handlers are sharable
        pipeline.addLast(DECODER);
        pipeline.addLast(ENCODER);
        pipeline.addLast(SERVER_HANDLER);
    }
});

...

@io.netty.channel.ChannelHandler.Sharable
public class CustomBusinessHandler extends SimpleChannelInboundHandler{...}

Upvotes: 0

forty-two
forty-two

Reputation: 12817

  1. Give the SocketFactory a single threaded executor, or
  2. put a shared , ExecutionHandler with a single threaded executor in the pipeline

Upvotes: 1

Related Questions