Associated MemoryAddress API

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Tue Mar 3 23:54:34 UTC 2020


>
>
> Basically:
>
>
> MemorySegment seg = 
> MemorySegment.allocateNative(MemoryLayouts.C_POINTER);
>
>
> MemorySegment segChild = 
> MemorySegment.allocateNative(MemoryLayouts.C_POINTER);
>
>
> segChild = segChild.setParent(seg);
>
>
> Then when closing seg, it'll also free segChild.

There's no great way to do that.

One option, if we added support for custom cleanup callback, would be to 
create an unchecked segment for 'seg' whose close closes both.

Another option would be to have some abstraction built on top of memory 
segments, which manages this more complex (and dependent) lifecycle - 
some sort of factory which gives out segments which are all tied to the 
same original segment (also managed by the factory). Something like this 
(rough attempt):

class DependentSegmentFactory implements AutoCloseable {

     final MemorySegment parent = 
MemorySegment.allocateNative(MemoryLayouts.C_POINTER);
     final List<MemorySegment> children = new ArrayList<>();

     MemorySegment makeNewSegment() {
          MemorySegment segment = 
MemorySegment.allocateNative(MemoryLayouts.C_POINTER);
          children.add(segment);
          return segment;
     }

     void close() {
           children.forEach(MemorySegment::close());
           parent.close();
     }
}

Ultimately, what you are looking for is some kind of operation which 
allows you to create one or more segments which share the same 
life-cycle, but probably with some kind of asymmetric relationship, so 
that only one segment in the group gets to decide when it's time to 
close everything down.

I've seen a similar problem in our libclang port:

https://github.com/openjdk/panama-foreign/blob/foreign-jextract/src/jdk.incubator.jextract/share/classes/jdk/internal/clang/TranslationUnit.java#L85

For which I've had to define an AllocationScope abstraction --- which 
has same name, accidentally, as the public API, but whose behavior is 
different:

https://github.com/openjdk/panama-foreign/blob/foreign-jextract/src/jdk.incubator.jextract/share/classes/jdk/internal/clang/AllocationScope.java


So I agree that at times it would be nice to be able to have more 
control over the lifecycle of related segments - and we need to think of 
ways in which to do that neatly (assuming we find a way to support this 
w/o making the API too cumbersome to use in the common case - which I 
assume will not want this level of fine-grained control).

Maurizio





More information about the panama-dev mailing list