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
java multithreading nio bytebuffer
Paul bellora
source share