Is Netty Channel.write thread safe?



我有一个Netty应用程序,我希望有多个线程写入频道。我只是想知道 Channel.write 是否线程安全?

从代码中可以看出,ChannelOutboundBuffer.addMessage()方法本身不是线程安全的。但是,写入通道是"线程安全的",因为 netty 在单个 I/O 线程中执行写入任务/方法。

它是线程安全的,因此您无需担心。

不,它是线程不安全的,因为Channel.write在其管道的 HeadContext 中调用ChannelOutboundBuffer.addMessageChannelOutboundBuffer.addMessage绝对是线程不安全的。看看这个代码:

 public void addMessage(Object msg, int size, ChannelPromise promise) {
     Entry entry = Entry.newInstance(msg, size, total(msg), promise);
     if (tailEntry == null) {
         flushedEntry = null;
         tailEntry = entry;
     } else {
         Entry tail = tailEntry;
         tail.next = entry;
         tailEntry = entry;
     }
     if (unflushedEntry == null) {
         unflushedEntry = entry;
     }
     // increment pending bytes after adding message to the unflushed arrays.
     // See https://github.com/netty/netty/issues/1619
     incrementPendingOutboundBytes(size, false);
 }

最新更新