Question about global SegmentScope
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Mon Apr 17 14:37:53 UTC 2023
On 17/04/2023 15:23, 刘希晨 wrote:
> Thank you for the clarification. I am stuck with my mind because I
> thought that if the SegmentScope() is global, then even if the
> MemorySegment Object has been GCed, the underlying memory won't be
> released, not until the JVM exit. (Is that correct? I think that's the
> difference between the global scope and the auto scope).
This is not correct.
The segment you get back from a native library has an "unknown scope"
(as said, in the Java 21, this is different from the "global" scope,
which is guaranteed to be always alive until VM termination). Segments
with "unknown" scopes can be accessed, but at your own risk, as the
region of memory backing the segment could be freed (in the general
case) at any time by the native library.
Now, in reality things are not as bleak as they sound - while _in
principle_ the region backing the segment might disappear w/o notice, in
practice a well-defined library will advertise who and when should
release the regioin of memory associated with a pointer that has been
returned by some function. But this is a detail that is typical buried
in the documentation of the function you are interacting with - it
cannot be expressed in the static type system of the C language and the
FFM API has no knowledge of it.
Maurizio
More information about the panama-dev
mailing list