How to free (close) a MemorySegment slice allocated to a resource by a parent allocator?

Radosław Smogura mail at smogura.eu
Fri Aug 26 19:36:48 UTC 2022


Hi Gevin,

Those are interesting questions.

First of all MemorySegment is a wrapper for pointer and length of data after this pointer. It does not represent physical memory – it’s more like C pointer.

In order to free memory you have to check it with allocator implementation.

Allocator can register itself with session to perform clean-up when session is closed, as memory session performs role of synchronizier between Java and C. When memory session get’s closed Java will throw exception, to prevent accessing potentially invalid segment.

I hope this clarified a bit.

Best regards,
Radoslaw Smogura

From: Gavin Ray<mailto:ray.gavin97 at gmail.com>
Sent: Friday, August 26, 2022 8:47 PM
To: panama-dev at openjdk.org<mailto:panama-dev at openjdk.org>
Subject: How to free (close) a MemorySegment slice allocated to a resource by a parent allocator?

Hello all,

I'm trying to finish the implementation of a Buffer Pool manager that uses the Foreign Memory API
The below may not be entirely correct (I'm new to the concept of memory management)

One thing I can't seem to figure out at all, is how to manually deallocate memory handed out to individual pages
I have a contiguous block of memory/arena used for the buffer pool, each page gets a PAGE_SIZE chunk

If I want to delete a page from the pool, is it just zeroing the memory, or do I want to close the slice that was allocated?

Thank you =)

Code below:
==========================================

class BufferPoolManager implements AutoCloseable {
    private static final int PAGE_SIZE = 4096;
    private static final int NUM_PAGES = 100;

    private final MemorySession allocator = MemorySession.openConfined();
    private final MemorySegment bufferPoolArena = allocator.allocate(NUM_PAGES * PAGE_SIZE);

    private final DiskManager diskManager;
    private final List<HeapFilePage> pages;
    private final List<Integer> freeList;

    public BufferPoolManager(String fileName) throws IOException {
        this.diskManager = new DiskManager(fileName);
        this.pages = new ArrayList<>();
        this.freeList = new ArrayList<>();
        for (int i = 0; i < NUM_PAGES; i++) {
            MemorySegment buffer = bufferPoolArena.asSlice(i * PAGE_SIZE, PAGE_SIZE);
            HeapFilePage page = new HeapFilePage(buffer);
            page.setPageId(i);
            pages.add(page);
            freeList.add(i);
        }
    }
}



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20220826/e14d98c3/attachment-0001.htm>


More information about the panama-dev mailing list