Unsafe making too strong assumptions about array alignment?
John Rose
john.r.rose at oracle.com
Tue May 27 23:39:19 UTC 2025
I would say it is either 0 mod 8 bytes or maybe sometimes 4 mod 8, but it’s always a compile time constant. At least for any single array type. On systems where 4 can happen, we might need to make some allowance for partial misalignment, if the hardware does not already. I hope we can hide some or all of that under the rug.
> On May 22, 2025, at 9:47 AM, 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.
> This can be seen when debugging through the following code which eventually calls `putLongUnaligned`:
>
> ```
> ByteBuffer buffer = ByteBuffer.wrap(new byte[Long.BYTES]);
> buffer.putLong(1);
> ```
>
> So my question is, does the JVM guarantee that the base address of the array is aligned by 8? Especially on 32-bit systems?
> If the JVM guaranteed this, then these unaligned methods should be safe I assume since the `offset` passed to them includes the `arrayBaseOffset` and therefore if the elements were not aligned relative to the base address of the array, it would be detected as unaligned and handled properly.
>
> I hope you can help me better understand this, thanks a lot!
>
> Kind regards
>
More information about the panama-dev
mailing list