虽然不能保证 ByteBuf 是线程安全的,但是这个用例可以吗?

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

(我知道ByteBuf documentation does not say anything about thread safety。)

我有一个 ByteBuf 我希望以非常非常具体的方式在两个线程之间共享。

对于这个用例,我可以控制在两个线程中执行的代码。

具体来说,线程一,即事件循环,将按顺序从ByteBuf读取。它永远不会写,也不会调用除readRetainedSlice, isReadable, asReadOnly and readableBytes().

以外的任何方法

线程二(不是事件循环)将使用其 writeBytes 方法将字节 附加到 ByteBuf。它不会在 ByteBuf.

上调用其他方法

不会在此 ByteBuf 上调用其他方法。

ByteBuf itself is an abstract class with no fields 并且没有与线程相关的文档,因此显然不能保证任何给定的实现在这种使用模式下都是线程安全的。

但是 实际上 来说,所有 Netty ByteBuf 实现都是从 AbstractByteBuf 继承而来的,至少在这个特定的用例中,这似乎是线程安全的?或者我必须安排对 ByteBuf 的写入也发生在事件循环中吗?

由于您的用例涉及 ByteBuf 的顺序访问语义通过其 readRetainedSlicewriteBytes 方法公开(以及其他) ,你保证它的可读字节区和它的可写字节区不会重叠,因此不会发生多线程访问冲突的危险。使用 isReadableasReadOnlyreadableBytes 对线程安全没有影响 对于您的特定用例 但会增加额外的安全层。