How to explicit deallocate memory segment?
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Tue Oct 17 09:59:33 UTC 2023
On 17/10/2023 00:54, tison wrote:
> A confined/shared arena is defined to associate the same lifecycle for
> all memory segments it allocates - that they will be deallocated on
> the arena closed.
>
> But it can be normal that I want to preallocate a large arena and
> allocate/deallocate memory segments on this arena. In this case, what
> design pattern can help since there is no explicit deallocate method
> (I found we have one in the early release but it's absent now, why?)
>
> Best,
> tison.
I think the pattern you describe is that of a memory pool. That is, some
memory segment is allocated at the start of the application, and its
contents are recycled by multiple clients.
This can be done using a custom arena, such as the one decribed here:
https://cr.openjdk.org/~mcimadamore/panama/why_lifetimes.html
Note the example:
```
SlicingPool pool = new SlicingPool();
...
try (Arena slicingArena1 = pool.acquire()) {
MemorySegment segment1 = slicingArena1.allocate(100);
} // 'segment1' becomes invalid here
...
try (Arena slicingArena2 = pool.acquire()) {
MemorySegment segment2 = slicingArena2.allocate(100);
} // 'segment2' becomes invalid here
```
That is, clients can come and go, and they will just get a _new_ arena
that is based off a slice of the original segment. This simple
implementation of course only works in a single thread.
There were other examples of memory pools provided in the past which
also worked across multiple threads:
https://github.com/openjdk/panama-foreign/pulls
(unfortunately this is a rather old PR, and its code has diverged from
the current API, but it could be used as inspiration).
Maurizio
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20231017/f0d34394/attachment.htm>
More information about the panama-dev
mailing list