← Back to context

Comment by amai

3 years ago

Could a Java version of the future maybe also manage memory with a try-with-resources block ?

Your wish is granted :D

https://openjdk.org/jeps/424

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

Java and the JVM has a garbage collector, and will likely always have, and GC makes memory management a lot simpler and safer, so while you could use try-with-resources for some kind of memory related resource, it likely would not be to make things safer, but to make things less safe and faster, and if you start doing that you will have significantly reduced safety compared to rust I think.