"Malloc/Free" Callbacks for Dynamic Off-heap MemorySegments

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Apr 16 11:26:54 UTC 2021


On 16/04/2021 11:55, Maurizio Cimadamore wrote:
> The answer to the former is "yes!" (and we do so via the 
> SegmentAllocator interface in the new API, which accepted anywhere a 
> segment needs to be allocated). 

To be clear, this is what I had in mind, which might, or might not be 
what you were alluding to:

```
public class TestAllocator {
     public static void main(String[] args) {
         TrackingAllocator trackingAllocator = new TrackingAllocator();
         MemorySegment segment = 
trackingAllocator.allocate(MemoryLayouts.JAVA_DOUBLE);
         segment.scope().close();
     }

     static class TrackingAllocator implements SegmentAllocator {
         @Override
         public MemorySegment allocate(long bytesSize, long 
bytesAlignment) {
             ResourceScope scope = ResourceScope.newConfinedScope();
             MemorySegment segment = 
MemorySegment.allocateNative(bytesSize, bytesAlignment, scope);
             onAllocate(segment);
             scope.addOnClose(() -> onClose(segment));
             return segment;
         }

         void onAllocate(MemorySegment segment) {
             System.out.println("Allocated - " + segment);
         }

         void onClose(MemorySegment segment) {
             System.out.println("Freed - " + segment);
         }
     }
}
```

This prints, when executed:

```
Allocated - MemorySegment{ id=0x1ee42522 limit: 8 }
Freed - MemorySegment{ id=0x1ee42522 limit: 8 }
```

I'm sure this is overly simplistic, but it should illustrate a possible 
approach to do tackle the issues you describe?

Maurizio



More information about the panama-dev mailing list