Unsafe.{get,put}-X-Unaligned; Efficient array comparison intrinsics

Andrew Haley aph at redhat.com
Sun Mar 8 11:13:41 UTC 2015

On 03/07/2015 09:23 PM, Peter Levart wrote:

> I see you're not using Unsafe.unalignedAccess() method in Unsafe
> code at all. So the approach to use this information and decide
> whether to use Unsafe.getXXX() or Unsafe.getXXXUnaligned() is left
> to the user of Unsafe API.

I don't think that there is any reason to keep library code from being
able to discover whether this machine can do unaligned loads.
However, there is now no reason to use Unsafe.getXXX() on an unaligned
word.  unalignedAccess() is for tuning, not correctness.

> That's OK if you think this approach is a better division of
> concerns (Unsafe being low-level), but in Heap-X-Buffer you are only
> using Unsafe.get|putXXXUnaligned() and don't consider using
> get|putXXX directly when unalignedAccess() == true.

Right, because there's no point in doing so when unalignedAccess() ==
true because the exact same code will be generated.  In my Utopian
world nothing except Unsafe would have to deal with issues such as
this.  However, I think that people writing library code (e.g. array
comparison intrinsics) might still need to know.

The problem is that in reality unalignedAccess() isn't as simple as a
binary yes/no.  For example, on some machines unaligned accessess
might be significantly slower than aligned ones but still work; so,
unalignedAccess() will (?) return true even though it might not be
ideal.  Library code is then to have to use some sort of heuristic to
decide whether to use e.g. getLongUnaligned() or getInt() (when
comparing e.g. int arrays).

I wonder if on all machines it's worth using getLongUnaligned() for
int array comparisons.  I don't know.  I hope it is, but I suspect it

> In java.nio.Bits, the Unsafe.unalignedAccess() is used to lazily
> initialize the Bits.unaligned static field. This lazy initialization
> is unnecessary now and 'unaligned' field can be made final.

I agree, but there are quite a few other places which could also be
improved by the use of this API, and every patch must stop somewhere.
This one is the first.


More information about the hotspot-compiler-dev mailing list