When programming with Netty, we often initiate write operations from the user thread, not the Netty thread pool, because we cannot do much time-consuming operations in the Netty event callbacks. So here's the problem –
1, is Writeandflush thread-safe?
2, whether the use of locks, resulting in decreased concurrency performance
Let's look at the code – in Defaultchannelhandlercontext
@Override Public channelfuture Writeandflush (Object msg, Channelpromise Promise) { defaultchannelhandlercontext next; = Findcontextoutbound (mask_write); Referencecountutil.touch (msg, next); Next.invoker.invokeWrite (Next, MSG, promise); = Findcontextoutbound (mask_flush); Next.invoker.invokeFlush (next); return promise;}
In the Defaultchannelhandlerinvoker.java
@Override Public voidInvokewrite (Channelhandlercontext ctx, Object msg, Channelpromise promise) {if(msg = =NULL) { Throw NewNullPointerException ("MSG"); } if(!validatepromise (CTX, Promise,true)) { //Promise cancelledreferencecountutil.release (msg); return; } if(Executor.ineventloop ()) { Invokewritenow (CTX, MSG, promise); } Else{Abstractchannel Channel=(Abstractchannel) Ctx.channel (); intSize =channel.estimatorhandle (). Size (msg); if(Size > 0) {Channeloutboundbuffer buffer=Channel.unsafe (). Outboundbuffer (); //Check for NULL as it could be set to NULL if the channel is closed already if(Buffer! =NULL) {buffer.incrementpendingoutboundbytes (size); }} Safeexecuteoutbound (Writetask.newinstance (CTX, MSG, size, promise), promise, MSG); } }
Private void Safeexecuteoutbound (Runnable task, channelpromise Promise, Object msg) { try { Executor.execute (Task); Catch (Throwable cause) { try { promise.setfailure (cause); finally { referencecountutil.release (msg); }}}
It is visible that Writeandflush is directly write if executed within the Netty thread pool, otherwise it will be inserted as a task into the Netty thread pool execution.
"The Netty authoritative guide" writes
By invoking the Execute (Runnable Task) method of Nioeventloop, Netty has many system tasks, and the main reason for creating them is that when I/O threads and user threads simultaneously manipulate network resources, in order to prevent lock contention caused by concurrent operations, Encapsulating the actions of the user thread into a task into a message queue, executed by the I/O thread, allows for local non-locking.
Reference
Http://www.cnblogs.com/zemliu/p/3667332.html
Http://netty.io/5.0/xref/io/netty/channel/DefaultChannelHandlerInvoker.html
http://www.infoq.com/cn/articles/netty-version-upgrade-history-thread-part/
Thread safety and concurrency issues for Netty:writeandflush