使用Netty編程時,咱們常常會從用戶線程,而不是Netty線程池發起write操做,由於咱們不能在netty的事件回調中作大量耗時操做。那麼問題來了 –html
1, writeAndFlush是線程安全的嗎?java
2, 是否使用了鎖,致使併發性能降低呢編程
咱們來看代碼 – 在DefaultChannelHandlerContext中promise
@Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { DefaultChannelHandlerContext next; next = findContextOutbound(MASK_WRITE); ReferenceCountUtil.touch(msg, next); next.invoker.invokeWrite(next, msg, promise); next = findContextOutbound(MASK_FLUSH); next.invoker.invokeFlush(next); return promise; }
在DefaultChannelHandlerInvoker.java中安全
@Override public void invokeWrite(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg == null) { throw new NullPointerException("msg"); } if (!validatePromise(ctx, promise, true)) { // promise cancelled ReferenceCountUtil.release(msg); return; } if (executor.inEventLoop()) { invokeWriteNow(ctx, msg, promise); } else { AbstractChannel channel = (AbstractChannel) ctx.channel(); int size = channel.estimatorHandle().size(msg); if (size > 0) { ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); // Check for null as it may 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); } } }
可見,writeAndFlush若是在Netty線程池內執行,則是直接write;不然,將做爲一個task插入到Netty線程池執行。網絡
《Netty權威指南》寫到
經過調用NioEventLoop的execute(Runnable task)方法實現,Netty有不少系統Task,建立他們的主要緣由是:當I/O線程和用戶線程同時操做網絡資源時,爲了防止併發操做致使的鎖競爭,將用戶線程的操做封裝成Task放入消息隊列中,由I/O線程負責執行,這樣就實現了局部無鎖化。併發
參考
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/ide