Is it possible to use the FFM API to "free" a direct NIO buffer?

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Oct 6 11:33:24 UTC 2023


Hi Julien,
we do not have plans to expose arenas in direct buffers.

The way you get to deterministic deallocation of direct buffers is by 
creating a segment first, and then exposing a buffer view of the 
segment. That view will be backed by whatever Arena you used to create 
the segment, so, if it's a confined arena, you can use it to also free 
the segment (and hence the buffer view).

This process is explained in a brand new section of JEP 454:

https://openjdk.org/jeps/454

(see "Memory segments and byte buffers").

If you control the allocation of the direct buffers (which I think you 
do, otherwise why trying to free them?) this works fine, and doesn't 
require code to make extensive changes: you only need to create a 
"factory" for direct buffers which, internally, uses memory segments and 
arenas.

Note that your reinterpret call will not work in the way you 
desire/expect. What you are doing there is constructing a segment out of 
a byte buffer and then trying to reinterpret the segment to have new 
temporal bounds. This will NOT cause the buffer to be released when the 
arena is closed. You have to do it the other way around: first create 
the segment, then the buffer.

Maurizio


On 06/10/2023 12:00, Julien wrote:
> Hello
>
>
> Some third party APIs are still using direct NIO buffers despite the numerous
> advantages of the FFM API. MemorySegment.asByteBuffer() and
> MemorySegment.ofBuffer(Buffer) are helpful to write some new code with the FFM
> API while using some APIs heavily relying on direct NIO buffers. I still have to
> use some fragile source code to "free" the direct NIO byte buffers in a timely
> manner in the meantime as some third party APIs won't migrate to FFM API very
> soon, there will be a transition phase. What is the good practice to "free"
> direct NIO buffers right now? Is the source code below a good illustration of
> what should be done?
>
>
> final Arena arena = Arena.ofConfined();
>
> MemorySegment.ofBuffer(myDirectByteBuffer).reinterpret(arena, null);
>
> arena.close();
>
>
> I assume that MemorySegment.ofBuffer(Buffer) uses an automatic arena internally.
>
>
> Best regards.


More information about the panama-dev mailing list