import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

public class Test01 {

    public static void main(String[] args) throws IOException {
        MemorySegment segment = Arena.ofShared().allocate(ValueLayout.JAVA_INT.byteSize());
        Arena arena = Arena.ofShared();
        AtomicBoolean cleanup_called = new AtomicBoolean(false);
        AtomicReference<MemorySegment> ms4Cleanup = new AtomicReference();
        Consumer<MemorySegment> cleanup = (s) -> {
            System.out.println("byte-size: " + s.byteSize() + ". Arena closed XXX");
            cleanup_called.set(true);
            ms4Cleanup.set(s);
            System.out.println(s.address());
        };

        //Works as expected when arena is closed
        //MemorySegment reinterpreted_1 = csd1.segment().reinterpret(arena, cleanup);
        
        //cleanup not called with this variant
        MemorySegment reinterpreted_1 = segment.reinterpret(segment.byteSize(), arena, cleanup);
        arena.close();
        System.out.println("cleanup called? " + cleanup_called.get());
        System.out.printf("orig: %d, re: %d, cu: %d" ,segment.address(), reinterpreted_1.address(), ms4Cleanup.get().address());
    }
}
