Fix arena lifetime in record constructor #360
No reviewers
Labels
No labels
bug
dependencies
documentation
duplicate
enhancement
github_actions
good first issue
help wanted
invalid
java
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
java-gi/java-gi!360
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "fix-record-arena"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
When creating a record (struct) instance from Java, the fields can be set from the constructor. Fields that require memory allocation, use an Arena, as does allocating the struct itself. When no arena parameter is set,
Arena.ofAuto()is used. However, the fields used anArena.ofAuto()that immediately became unreachable, and the allocated memory too (it is allocated in native code, and assigned in the field'sVarHandle, but theMemorySegmentis not stored in Java). As a result, the allocated memory for the field was released after the next GC run.The fix is to use one arena to allocate memory for the struct and the fields. The struct
MemorySegmentis stored in Java, so the arena is not closed until the Java object is garbage-collected.One problem that remains, is that re-assigning the field to another value, will allocate a new
MemorySegment, but not free the old one. However, this is only the case for parameter allocations in the constructor, and very hard to resolve. If this is an issue, it is better to use the parameterless constructor and set the fields separately.