做学校子网站,wordpress 洛米,高端装饰公司网站设计,wordpress浮动导航菜单使用Netty编程时#xff0c;我们经常会从用户线程#xff0c;而不是Netty线程池发起write操作#xff0c;因为我们不能在netty的事件回调中做大量耗时操作。那么问题来了 – 1#xff0c; writeAndFlush是线程安全的吗#xff1f; 2#xff0c; 是否使用了锁#xff0c;…使用Netty编程时我们经常会从用户线程而不是Netty线程池发起write操作因为我们不能在netty的事件回调中做大量耗时操作。那么问题来了 – 1 writeAndFlush是线程安全的吗 2 是否使用了锁导致并发性能下降呢 我们来看代码 – 在DefaultChannelHandlerContext中 Overridepublic 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中 Overridepublic void invokeWrite(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {if (msg null) {throw new NullPointerException(msg);}if (!validatePromise(ctx, promise, true)) {// promise cancelledReferenceCountUtil.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 alreadyif (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.htmlhttp://netty.io/5.0/xref/io/netty/channel/DefaultChannelHandlerInvoker.htmlhttp://www.infoq.com/cn/articles/netty-version-upgrade-history-thread-part/转载于:https://www.cnblogs.com/Binhua-Liu/p/5295365.html