ByteBuffer views, alignment, word tearing

Andrew Haley aph at
Mon Jul 11 15:08:15 UTC 2016

I saw a few ACCEPTABLE_SPEC results for ByteBuffer views in jcstress.
This results from word tearing.  I was rather surprised, because I'd
worked on the HeapByteBuffer implementation, and I knew that on we
would't expect to see any word tearing for HeapByteBuffers or
DirectByteBuffers, at least for aligned word fetches and stores.

Unfortunately, we're still doing this in e.g. ByteBufferAsIntBufferL:

    public int get(int i) {
        return Bits.getIntL(bb, ix(checkIndex(i)));

where Bits.getIntL is defined as:

   static int getIntL(ByteBuffer bb, int bi) {
        return makeInt(bb._get(bi + 3),
                       bb._get(bi + 2),
                       bb._get(bi + 1),
                       bb._get(bi    ));

instead of what I'd thought we were doing, which was:

    public int get(int i) {
        return bb.getInt(ix(i));

... so we get slow byte-at-a-time implementations of all the getX and
putX methods -- with no HotSpot intrinsic optimizations.  And we get
word tearing even though the data in a ByteBuffer view is always

It never occurred to me that the ByteBuffer views didn't defer to the
ByteBuffer.{get,put} methods.  Either that or I forgot, but I should
have fixed ByteBuffer views at the same time as HeapByteBuffer.

It's not a huge job to fix this, but rather late for JDK 9.


[P.S.  It's a little bit more complicated than this because a
ByteBuffer view has the endianness that its parent had when the view
was created.  But that's not hard to do.]

More information about the core-libs-dev mailing list