Summary
The changes described here allow the Foreign Function & Memory API to create a memory segment from an arbitrary Buffer instance, regardless of its concrete type.
Problem
The MemorySegment class has a static factory, namely MemorySegment::ofByteBuffer. This factory can be used to create a memory segment view out of a ByteBuffer instance (whether on- or off-heap).
It is not possible to create a memory segment view out of other Buffer subclasses, such as IntBuffer, LongBuffer, etc. This creates an asymmetry with respect to the Java Native Interface (JNI), since JNI clients can access the base address of any Buffer instance, regardless of its concrete type (see the JNI function GetDirectBufferAddress).
Solution
We propose to generalize the ofByteBuffer factory as follows:
- change the parameter type to take any
Buffer - change the name of the factory to
ofBuffer
These changes allow clients to create memory segments views out of Buffer instance of any kind - meaning that clients can now wrap an IntBuffer into a MemorySegment in case they want to pass that segment to a foreign function.
We are not proposing to make changes to the dual method of the API considered here, namely the instance method MemorySegment::asByteBuffer. This simply doesn't seem worth, due to asymmetries in the Buffer API. For instance, off-heap buffers can only created form ByteBuffer::allocateDirect. So, to create an off-heap IntBuffer, clients have to first create a direct ByteBuffer then to view that buffer as an IntBuffer (usingByteBuffer::asIntBuffer).
In other words, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer are not first-class citizens of the Buffer API. As such it would not be possible to map many memory segments into an IntBuffer; in fact, the only segment we could safely map into an IntBuffer would be an heap segment backed by an int array (e.g. created from MemorySegment::ofArray(int[]). As such it doesn't seem worth adding a lot of API surface (in terms of additional overloads) for such a corner case.
Specification
A link to the specdiff for the proposed changes can be found here:
http://cr.openjdk.java.net/~mcimadamore/8286715/v1/specdiff_out/overview-summary.html
A link to the javadoc for the proposed changes can be found here:
http://cr.openjdk.java.net/~mcimadamore/8286715/v1/javadoc/java.base/module-summary.html
A zip file containing both has been attached to this CSR.
- csr of
-
JDK-8286715 Generalize MemorySegment::ofBuffer
-
- Resolved
-