Saving State in Netty ChannelHandler

The netty documentation suggests using instance variables in ChannelHandlers to track channel status. He does not mention that you should use mutable variables or use any other synchronization technique to ensure that threads are always displayed.

For example, using this handler for each connection:

class Handler extends SimpleChannelUpstreamHandler { int count = 0; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ++count; } } 

I would expect that many different threads from the netty thread pool would call this method, although not at the same time, and could potentially see an inconsistent view, which leads to an inaccurate count.

This is true? or is there some kind of synchronization going on inside netty that will lead to painting the record in the count field?

+4
source share
2 answers

If you do not have an executor in your pipeline and your handlers are executed exclusively in I / O workflow threads, then you are fine, because Netty guarantees that this instance of the pipeline is always called from the same workflow.

If you add an execution handler to your pipeline, then you're fine if you use Netty OrderedMemoryAwareThreadPoolExecutor.

If you access the pipeline from a thread other than Netty, or you have a non-OrderedMemoryAwareThreadPoolExecutor in your pipeline, you need synchronization.

I recommend that you review the following topics in the archives of the Netty User Forum.

http://netty.markmail.org/search/?q=Memory+visibility+in+handlers#query:Memory%20visibility%20in%20handlers+page:1+mid:cmtw5omcxbg67sho+state:results

http://netty.markmail.org/search/?q=Periodic%20TimerTask%20in#query:Periodic%20TimerTask%20in+page:2+mid:vwahepiois4eqwkp+state:results

+7
source

When you create a Netty ChannelPipeline , if you add an instance of your Handler to all channels, then yes, several threads will read / modify your data.

If you create a new Handler instance for each channel in your pipeline, as shown below, then you are safe, only one thread will access the processor in the pipeline at a time.

 ChannelPipeline p = Channels.pipeline(); pipeline.addLast("handler", new Handler()); 

Also take a look at Netty ChannelLocal as java ThreadLocal and you can set the state for each channel

+2
source

Source: https://habr.com/ru/post/1383537/


All Articles