Unsafe making too strong assumptions about array alignment?
some-java-user-99206970363698485155 at vodafonemail.de
some-java-user-99206970363698485155 at vodafonemail.de
Thu May 22 16:46:37 UTC 2025
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