Ersin Er
Ersin Er

Reputation: 1045

Do messages sent via Netty's Channel.write() preserve their order when begin sent out to the network?

I am doing some sort of encryption which depends of the order of messages sent via a Netty channel. What I am expecting is that if I write message A before message B to a channel then they should be sent to the remote socket in the same order I have written them to the channel. So is the case I need already supported by Netty?

On the other hand Netty's Channel accepts concurrent write calls and I am in doubt my requirement can already met. I had to synchronize on a statefull (a per channel one) encoder today due to currupt state of a data structure. However I am still not sure whether the in-filter synchronization will help my need.

Upvotes: 2

Views: 2235

Answers (3)

Osiris Team
Osiris Team

Reputation: 101

The above answers are wrong, at least for Netty >= 4.1.96.

Internally the write task is forwarded to the next available executor thread (see AbstractChannelHandlerContext.write() method), thus resulting in messages sent out of order.

You can prevent this behavior by setting the maximum amount of threads to 1 for your EventLoopGroup. Note that this is not optimal since you lose multithreaded reads, that's why I am working on a library which fixes this: https://github.com/Osiris-Team/jlib

Upvotes: 0

aoak
aoak

Reputation: 1013

Answer picked up from this issue. (Thanks Scottmitch@github).

Netty can provide "ordering" in the following situations:

  1. You are doing all writes from the EventLoop thread; OR
  2. You are doing no writes from the EventLoop thread (i.e. all writes are being done in other thread(s)).

It is subtle but important thing to remember as it can cause painful bugs. If some channel.write() calls are coming from application threads and some are coming from EventLoop then the writes can seem out of order from application's perspective. See more details on the linked issue.

This question seems to be the top search result for Netty write ordering, so wanted to make sure it mentions this important caveat.

Upvotes: 3

Norman Maurer
Norman Maurer

Reputation: 23567

Yes, the messages will get transfered in the same order as you call Channel.write(..). There is nothing you need to worry about here.

Upvotes: 6

Related Questions