java.nio.*Buffer read/write atomicity (original) (raw)

Zhong Yu zhong.j.yu at gmail.com
Wed Dec 19 23:23:07 UTC 2012


Users are unlikely to expect multi-byte atomicity on a ByteBuffer.

However they are more likely to expect int-width atomicity on an IntBuffer view of a ByteBuffer; such atomicity is unfortunately not guaranteed either.

Zhong Yu

On Wed, Dec 19, 2012 at 11:48 AM, Aleksey Shipilev <aleksey.shipilev at oracle.com> 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