Unsafe making too strong assumptions about array alignment?
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Thu May 22 17:00:20 UTC 2025
On 22/05/2025 17:46, some-java-user-99206970363698485155 at vodafonemail.de
wrote:
> Hello,
>
> I was reading https://bugs.openjdk.org/browse/JDK-8318966 which says:
>
>> array elements of a byte[] can at most be assumed to be be 1-byte
>> aligned (no alignment, really)
>
> The JDK HeapByteBuffer is using the `...Unaligned` methods of
> jdk.internal.misc.Unsafe, e.g. `putLongUnaligned`. But the in latest
> JDK versions these methods only check the given `offset`, they don't
> actually check the base address of the array.
Note: I don't think any JDK version ever checked the base address of the
array -- this is simply not known at the Java level.
When accessing array element using Unsafe, a client has to provide two
coordinates:
* the array object they want to access (a reference)
* the offset of the element from the start of the object array
There has never been an alignment check in there -- because we simply
don't know the physical address of the array (the GC knows, but we don't).
Note that putLongUnaligned doesn't mean: this *is* an unaligned store.
It means this *can* be an unaligned store.
In other words, we are using the most general possible Unsafe access
primitive -- because we don't know what the underlying alignment will
be. Note also that `putLongUnaligned` is a VM intrinsics, and in most
cases there will be no real performance difference between this and the
aligned variant (so, in most cases, just using the unaligned primitive
is better/more general, which is why both ByteBuffer and FFM do that).
I hope this helps clarifying the confusion?
Maurizio
More information about the panama-dev
mailing list