java.nio.*Buffer read/write atomicity

Aleksey Shipilev aleksey.shipilev at oracle.com
Wed Dec 19 17:48:20 UTC 2012


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