[foreign-jextract] Closing sliced segment closes original segment

Filip Krakowski krakowski at hhu.de
Tue Aug 4 14:01:16 UTC 2020


Hi,

thanks for clearing that up. I searched within the "Closing a memory 
segment" section and overlooked that the "Memory segment views" section 
(https://github.com/openjdk/panama-foreign/blob/foreign-jextract/src/jdk.incubator.foreign/share/classes/jdk/incubator/foreign/MemorySegment.java#L128-L132) 
clarifies this behaviour.

I like to put AutoClosables inside of try-with-resources statements 
whenever they are used within a limited scope (like accessing a native 
String and copying it to a Java String). Removing the CLOSE access mode 
would lead to an Exception in this case.

I don't know if this makes sense, but I would expect MemorySegments to 
behave like (direct) ByteBuffers (slices) in this context, since the 
slice's memory is not released automatically (using a Cleaner) after the 
slice gets garbage collected. Is there a specific reason as to why child 
segments close their parent segments? If I got it right, the client 
would need to check if the segment has the CLOSE access mode set to 
decide if it may close the segment or not.

Best regards,
Filip

On 04.08.20 15:19, Maurizio Cimadamore wrote:
>
> On 04/08/2020 14:06, Filip Krakowski wrote:
>> Hi,
>>
>> I had a couple of IllegalStateExceptions stating that the segment I 
>> tried to close was already closed. After some debugging I found out 
>> this is caused by using a try-with-resources statement in combination 
>> with a MemorySegment (slice) returned by a field access ( try(var 
>> slice = struct.field$addr(originalsegment) { ... } ). After the 
>> statement the slice gets closed which also happens to close the 
>> original MemorySegment. I find this very confusing and would like to 
>> ask if this is intended behaviour or a bug.
>
> This is the intended behavior, and is documented in the API javadoc.
>
> When using the memory segment API directly, you can protect against 
> this (if you so wish) by making the sliced segment not closeable (see 
> MemorySegment::withAccessModes), before sharing it with a client.
>
> In this case the offending party is jextract - so I think we'll have 
> to do something in the extracted code to prevent this issue e.g. have 
> jextract mark the returned slice as non-closeable, to make it clear 
> that in no way the returned segment can have lifecycle side-effects on 
> the original segment.
>
> Thanks
> Maurizio
>
>>
>> Best regards,
>> Filip
>> Email Signature



More information about the panama-dev mailing list