Unsafe making too strong assumptions about array alignment?
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Mon May 26 12:23:59 UTC 2025
>
> might perform a misaligned store. The obvious response is that such
> systems must not allocate objects at less than the maximum (presumably
> 64-bit) alignment.
Yes and no.
IIUC, `offset` here is not the base address of the array -- but the
offset at which array elements start. And such offset can indeed be only
4-byte aligned in some cases.
For instance, if I do this using jshell on a JDK 22 x86 build, I get:
```
jshell> Unsafe.ARRAY_SHORT_BASE_OFFSET
$2 ==> 12
```
The same query returns 16 on a regular x64 JVM.
All this said, the physical address accessed by the JVM will be some
```
addr(array) + offset
```
So the implementation of `Unsafe::putLongAligned` morally behaves like this:
```
if ((addr(base) + offset) % 8 == 0) {
putLong(base, offset ... );
}
```
But, as Andrew suggests, if `base` is guaranteed to be a multiple of 8,
we can effectively ignore it for the purpose of the modulo operator
(e.g. N + X % 8 == X if N % 8 == 0).
Because of this, _under that assumption_, the Unsafe Java code is
correct -- e.g. it will never attempt to perform an aligned store at an
unaligned physical address.
And that assumption is indeed how a regular JVM implementation works,
see also:
https://shipilev.net/jvm/anatomy-quarks/24-object-alignment/
Maurizio
More information about the panama-dev
mailing list