JDK-8325879 : Release Note: Removal of Aligned Access Modes for `MethodHandles::byteArrayViewVarHandle`, `byteBufferViewVarHandle`, and Related Methods
  • Type: Sub-task
  • Component: core-libs
  • Sub-Component: java.lang.invoke
  • Affected Version: 23
  • Priority: P3
  • Status: Resolved
  • Resolution: Delivered
  • Submitted: 2024-02-14
  • Updated: 2024-07-31
  • Resolved: 2024-02-16
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 23
23Resolved
Description
The var handle returned by `MethodHandles::byteArrayViewVarHandle` no longer supports atomic access modes, and the var handle returned by `MethodHandles::byteBufferViewVarHandle` no longer supports atomic access modes when accessing heap buffers. Additionally, the `ByteBuffer::alignedSlice` and `ByteBuffer::alignmentOffset` methods are updated to reflect these changes. They no longer report aligned slices or offsets for heap byte buffers when the accessed 'unitSize' is greater than 1. They instead throw an `UnsupportedOperationException` in those cases.

The removed functionality was based on an implementation detail in the reference JVM implementation that is not mandated by the JVM specification. Therefore, it is not guaranteed to work on an arbitrary JVM implementation. This also allows the reference implementation to align array elements more loosely, if it is deemed beneficial [1](https://bugs.openjdk.org/browse/JDK-8314882).

Affected clients should consider using direct (off-heap) byte buffers, for which aligned access can reliably be guaranteed. Or they should use a `long[]` to store their data, which has stronger alignment guarantees than `byte[]`. A `MemorySegment` backed by a `long[]` array can be accessed through an atomic access mode and any primitive type, using the newly introduced Foreign Function and Memory API [3](https://bugs.openjdk.org/browse/JDK-8310626) as follows:

```
long[] arr = new long[10];
MemorySegment arrSeg = MemorySegment.ofArray(arr);
VarHandle vh = ValueLayout.JAVA_INT.varHandle(); // accessing aligned ints
vh.setVolatile(arrSeg, 0L, 42); // 0L is offset in bytes
long result = vh.getVolatile(arrSeg, 0L); // 42
```