Adding latency in Netty Server

240 views Asked by At

What is the best way to add latency to a Netty Server for testing? If a simple Thread.sleep(n) is added before the writeAndFlush(), the handler doesn’t become free to process the next request until the writeAndFlush() is executed, which is necessary in simulating random requests in a load test to get latency. What happens now with the Thread.sleep(n) is that the following request is not received by channelRead() until the previous one returns the ChannelFuture from the writeAndFlush(). Any suggestions?

1

There are 1 answers

0
Nikita On

Well, you can schedule the task to Netty's event loop with required delay in handler's channelRead method:

ctx.executor().schedule(() -> {
    ctx.writeAndFlush(...);
}, 100, TimeUnit.MILLISECONDS);

It won't block current thread and will execute asynchronously. But don't forget to release incoming ByteBuf inside the task to avoid buffer leaks.