javathread-safetydirect-buffer

Does absolute version of put() for for direct int buffer require synchronization?


I have a use of direct buffers, where a direct buffer is allocated and use like this:

ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
IntBuffer buffer1 = buffer.asIntBuffer();
buffer1.limit(1024);
buffer.position(4096);
IntBuffer buffer2 = buffer.asIntBuffer();

Then both buffer1 and buffer2 can be used from multiple threads with absolute get and put. It seems like nothing in the documentation specifies that reads and writes would be atomic (in the same sense as writing and reading a regular java array, ignoring visibility) in such a case, even though as far as I can tell from the underlying implementation it is going to be.

In this use case, if it was a regular java array, I wouldn't need any extra synchronization for accessing it as other existing synchronization would guarantee happens-before relationship. With direct buffers, as far as I can see, going strictly by the documentation, it seems like I would need to synchronize access to those buffers. Am I missing something that would allow me to skip synchronization?


Solution

  • The class Buffer contains this statement about thread safety:

    Thread safety

    Buffers are not safe for use by multiple concurrent threads. If a buffer is to be used by more than one thread then access to the buffer should be controlled by appropriate synchronization.

    No subclass of Buffer contains any additional statements about thread safety, so you must assume that this statement also applies to direct buffers and its varaints.