Comment by kaba0
3 years ago
Your wish is granted :D
Though there was nothing inherent to ever block you from doing it (just create an object that implements Closeable, and malloc in the constructor, free in the close method), this new API makes it quite great. The basic API gives you a SegmentScope which denotes a lifetime, and MemorySegments that point to a memory region (pointer+size+layout+scope). MemorySegments have both spatial and temporal safety, so accessing memory out of boundary will only throw an exception instead of corrupting memory, while any access outside the lifetime of the scope is forbidden. Oh, and they are also thread-safe, only optionally being shared between threads.
So in practice it you can write something like
try (var arena = Arena.openConfined()) {
MemorySegment segment = arena.allocate(someLayout);
// use segment
} // memory will be deallocated here
That's a nice improvement over sun.misc.Unsafe .
Nice. Thank you for pointing that out.