Although ByteBuf is not guaranteed to be thread-safe, will this use case be OK?

Viewed 126

(I know that the ByteBuf documentation does not say anything about thread safety.)

I have a ByteBuf that I wish to share between two threads in a very, very specific way.

I have control over the code executed in both threads for this one use case.

Specifically, thread one, which is the event loop, will be reading from the ByteBuf in sequential order. It will never write, nor will it call any method other than readRetainedSlice, isReadable, asReadOnly and readableBytes().

Thread two, which is not the event loop, will be appending bytes to the ByteBuf using its writeBytes method. It will call no other method on ByteBuf.

No other method will be called on this ByteBuf.

ByteBuf itself is an abstract class with no fields and no documentation related to threads so obviously there can be no guarantee that any given implementation of it will be thread safe with this usage pattern.

But practically speaking, are all Netty ByteBuf implementations descended from AbstractByteBuf, which would seem to be thread safe at least in this particular use case? Or must I arrange the writes to my ByteBuf to happen on the event loop as well?

1 Answers

Since your use case involves only the sequential access semantics of ByteBuf exposed (among others) by its readRetainedSlice and writeBytes methods, you're guaranteeing its readable bytes area and its writable bytes area won't overlap, hence, no multithreading access conflict hazard will occur. The use of isReadable, asReadOnly and readableBytes have no effect on thread safety for your specific use case but will add an extra layer of safety.

Related