Why are absolute reads from ByteBuffer not considered thread safe?

My use case requires a direct allocation of ByteBuffer , which is written once and then read by many parallel threads. All readings are absolute, so I never deal with the state of the buffer (position, limit, label).

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

ByteBuffer safety is described in Buffer JavaDoc; the short version is that buffers are not thread safe. Obviously, you cannot use relative positioning from multiple threads without a race condition , but even absolute positioning is not guaranteed (no matter what you might think after looking at implementation classes) .

(emphasis mine)

Because of this warning, I precede every reading from the byte buffer with a duplicate call. It is quite simple, but the additional distribution of objects on each separate reading makes me curious why this is really necessary.

Despite the fact that Kate was not aware of this, I looked at the OpenJDK implementation of absolute reading 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 "retrieves the value from the given memory address".

I understand that there may be various implementations, but what reasonably cannot be thread safe with respect to this operation? Is the Buffer contract simply dropping to guarantee thread safety for absolute readings, to avoid confusion with a partially thread safe class? Or, if the warning is warranted for writing at the same time, how about my situation where the byte buffer does not modify after creation? Also, will anything change when using a MappedByteBuffer instead?

on this topic:

  • What is the use of ByteBuffer in Java?
  • Java ByteBuffer - circular course
  • Atomic reading and then writing the ByteBuffer part in Java
  • Options to allow Java ByteBuffer to flow safely
+7
java multithreading nio bytebuffer
source share
1 answer

For a Buffer document, it states that buffer access should be synchronized. He does not say that it should not be used by different threads. Therefore, I think duplicate not required.

The fact that you cannot think of a reasonable non-threaded implementation of a method is more limited by your imagination than proof that caution is not required. Especially considering that you did not look at the Oracle Java code when Oracle indicated that the implementation was not thread safe.

My advice: do some reasonable synchronization when accessing the buffer. Even if a non-stream implementation is never implemented, it will not cost you much.

-one
source share

All Articles