Sub topic 3
Arenas: controlling when memory is freed
This chapter assumes you know what a MemorySegment is and can use try-with-resources. It also assumes Java 22 or later. Here you learn how an Arena decides when native memory is freed, and how to pick the right kind.
What an arena does
A memory segment is only a view of memory. It does not own that memory. An Arena owns it. Every segment you allocate from an arena lives exactly as long as the arena does. When the arena closes, all its segments are freed together, and any later access throws IllegalStateException.
This replaces manual free calls. You group allocations by lifetime and release them with one close().
The four arena kinds
| Factory method | Freed when | Accessible from | Can you call `close()`? |
|---|---|---|---|
| `Arena.ofConfined()` | You close it | The creating thread only | Yes, from the owner thread |
| `Arena.ofShared()` | You close it | Any thread | Yes, from any thread |
| `Arena.ofAuto()` | The garbage collector finds it unreachable | Any thread | No |
| `Arena.global()` | Never | Any thread | No |
Arena extends AutoCloseable, so confined and shared arenas work well in try-with-resources. The auto and global arenas throw UnsupportedOperationException if you call close().
Seeing the differences
The program below shows each rule in action.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class ArenaKinds {
public static void main(String[] args) throws Exception {
try (Arena confined = Arena.ofConfined()) {
MemorySegment s = confined.allocate(8);
Thread t = new Thread(() -> {
try {
s.get(ValueLayout.JAVA_INT, 0);
} catch (WrongThreadException e) {
System.out.println("confined: wrong thread");
}
});
t.start();
t.join();
}
try (Arena shared = Arena.ofShared()) {
MemorySegment s = shared.allocate(8);
s.set(ValueLayout.JAVA_INT, 0, 7);
Thread t = new Thread(() ->
System.out.println("shared: " + s.get(ValueLayout.JAVA_INT, 0)));
t.start();
t.join();
}
Arena auto = Arena.ofAuto();
try {
auto.close();
} catch (UnsupportedOperationException e) {
System.out.println("auto: cannot be closed");
}
}
}The confined segment rejects the second thread with WrongThreadException. The shared segment can be read from any thread. The auto arena refuses close().
Choosing an arena
Prefer a confined arena by default. It is the cheapest, and its thread check catches many bugs early. Use a shared arena only when threads really must touch the same memory.
Common errors
- Using a segment after closing. The access throws
IllegalStateException. This is safe, but it still means your lifetimes are wrong. Do not let a segment escape the try block. - Closing a confined arena from another thread. Only the owner thread may close it.
- Closing a shared arena while another thread is reading. The close waits for a safe point. Reads that start after it fail with
IllegalStateException. - Expecting prompt release from
ofAuto(). Memory is freed only after a garbage collection, which can happen much later. Native memory pressure does not trigger a collection. - Overusing
global(). Its memory is never released, so repeated allocation leaks.
Exercise
A worker pool of four threads fills one native buffer, and the main thread reads it after the workers finish. You want the memory freed deterministically right after reading. Which arena do you choose, and why not the others?
Show answer
Use Arena.ofShared(). Several threads access the buffer, which rules out ofConfined(), because other threads would throw WrongThreadException. You need deterministic release, which rules out ofAuto(), because the garbage collector decides when it is freed. It also rules out global(), because that memory is never freed. Close the shared arena after the main thread finishes reading.