简体   繁体   中英

Why are absolute reads from a ByteBuffer not considered thread-safe?

My use case requires a directly allocated ByteBuffer that is written to once and thereafter read by many concurrent threads. All reads are absolute and so I'm never concerned with the buffer's state (position, limit, mark).

This article on byte buffers by Keith Gregory warns that even absolute reads are not considered thread-safe:

ByteBuffer thread safety is covered in the Buffer JavaDoc; the short version is that buffers are not thread-safe. Clearly, you can't use relative positioning from multiple threads without a race condition, but even absolute positioning is not guaranteed (regardless of what you might think after looking at the implementation classes) .

(emphasis mine)

Because of this warning, I'm preceding every read from the byte buffer with a call to duplicate . This is easy enough, but the extra object allocation on every single read has me curious why it's actually necessary.

Despite Keith's wizardly disclaimer, I did look at OpenJDK's implementation of an absolute read from a direct byte buffer:

public byte get(int i) {
    return ((unsafe.getByte(ix(checkIndex(i)))));
}

You can see that it simply delegates to Unsafe.getByte(long) , which "fetches a value from a given memory address".

I understand that different implementations could exist, but what reasonably couldn't be thread-safe about this operation? Does the Buffer contract simply decline to guarantee thread-safety for absolute reads in order to avoid the confusion of a partially thread-safe class? Or if the warning is justified for concurrent writes, what about my situation, in which the byte buffer is unmodified after creation? Also, would anything change when using a MappedByteBuffer instead?

Related:

For one the Buffer documentation states that access to the buffer should be synchronized. It does no say that it must not be used by different threads. So I think a duplicate is not required.

That you can not think of a reasonable non-threadsafe implementation of some method or other is more a limit of your imagination than proof that caution is not necessary. Especially considering that you did not look at the Oracle Java code, when it was Oracle stating that the implementation is not threadsafe.

My advise: do some reasonable synchronization when accessing the buffer. Even if there never will be a non-threadsafe implementation it will not cost you much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM