java.nio.*Buffer read/write atomicity

Alan Bateman Alan.Bateman at oracle.com
Wed Dec 19 18:45:22 UTC 2012


On 19/12/2012 17:48, 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.
>
On memory model rules then there is is an outstanding bug to update the 
buffer spec with at least minimal properties. Doug might remember the 
discussion with Dave Dice about this a few years ago. I've always meant 
to do it but it never got to the top of the list.

That aside, I'm not aware of any discussion about the atomicity issue 
that you are concerned about now. As buffers are accessed directly in 
native code and by system calls then I think you would be limited to 
only specifying the put and get methods.

-Alan.



More information about the core-libs-dev mailing list