Tarandeep Gill
Tarandeep Gill

Reputation: 1536

Is Netty Channel.write thread safe?

I have a Netty app, where I want to have more than one threads to be writing to a channel. I was just wondering whether Channel.write is thread safe?

Upvotes: 7

Views: 5502

Answers (3)

Adrian Liu
Adrian Liu

Reputation: 385

As you can see from the code, the ChannelOutboundBuffer.addMessage() method itself is not thread safe. However, Writing channel is "thread safe" because netty executes the write task/method in the single I/O thread.

Upvotes: 7

yuguoliang
yuguoliang

Reputation: 9

No, it's thread-unsafe, because Channel.write calls ChannelOutboundBuffer.addMessage in its pipeline's HeadContext, and ChannelOutboundBuffer.addMessage is definitely thread-unsafe. Have a look at this code:

 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);
 }

Upvotes: 0

Norman Maurer
Norman Maurer

Reputation: 23567

It's thread safe so you don't need to worry.

Upvotes: 3

Related Questions