java.nio.*Buffer read/write atomicity

David Holmes david.holmes at
Wed Dec 19 20:37:46 UTC 2012


If multiple threads have to synchronize access to the buffer then the 
reads/writes do not need to be atomic. Atomicity is only needed when 
data races are allowed.


On 20/12/2012 3:48 AM, Aleksey Shipilev wrote:
> Hi guys,
> I wanted to cross-check what's the expected behavior of Buffers with
> respect to atomicity? Don't confuse the atomic operations (a la
> j.u.c.atomic.*) and the read/write atomicity. Here's the concrete
> example, should the assert always be true?
>    ByteBuffer buf = ByteBuffer.allocate(100);
>    (publish $buf to both threads properly)
>    (start both threads)
>    Thread 1:
>     buf.putInt(0, 42); // at position 0
>    Thread 2:
>     int i = buf.getInt(0); // at position 0
>     Assert.assertTrue( (i == 0) || (i == 42) )
> Javadoc is silent about that, except for noting Buffers are not supposed
> to be used from the multiple threads without synchronization. I would
> anyway advocate to follow the atomicity behavior of plain fields and
> arrays, and make these reads/writes atomic under the race.
> The apparent reason for at least BB to fail to be atomic is that we
> read/write larger values byte-by-byte. Luckily, it appears to be easy to
> fix (for a given endianness, we can just throw in the Unsafe call).
> Before going out and submitting the RFE, I wanted to crosscheck if
> somebody has strong feelings about this.
> Thanks,
> Aleksey.

More information about the core-libs-dev mailing list