Sub topic 3
Arenas: controlling when memory is freed
This chapter assumes you know how to allocate and read a MemorySegment, and that you are comfortable with try-with-resources. It targets Java 22, where the java.lang.foreign API is final. After reading it you should be able to pick the right arena for a piece of native memory and predict what happens when code touches that memory after the arena is closed.
What an arena does
A memory segment is a bounded view of memory. It does not decide when that memory is released. That job belongs to the segment's scope, which is represented by an Arena.
An arena has three responsibilities:
- It allocates segments through
Arena.allocate(...).ArenaextendsSegmentAllocator, so everything you can pass an allocator to also accepts an arena. - It owns every segment it allocates. All of them share the arena's lifetime.
- It frees all of those segments together when the arena is closed, or when the garbage collector decides the arena is unreachable.
Allocating from an arena means you do not free individual segments. You close one arena, and all its memory goes at once. This is the main way the FFM API avoids the leaks and double frees common in JNI and C.
The four kinds of arena
The Arena interface has four factory methods. They differ in who may close the arena, who may access its segments, and what ends its lifetime.
| Factory | Closeable? | Threads that may access segments | Memory freed when |
|---|---|---|---|
| `Arena.ofConfined()` | Yes, by the owner thread only | Owner thread only | `close()` is called |
| `Arena.ofShared()` | Yes, by any thread | Any thread | `close()` is called |
| `Arena.ofAuto()` | No | Any thread | The garbage collector finds the arena unreachable |
| `Arena.global()` | No | Any thread | Never, until the JVM exits |
Calling close() on an auto or global arena throws UnsupportedOperationException. Only the confined and shared arenas have a deterministic end of life.
Confined arenas
A confined arena belongs to the thread that created it. Only that thread can read or write its segments, and only that thread can close it. This restriction makes access cheap, because the runtime needs no synchronization to check that a segment is still alive.
Closing the arena frees its memory. A segment that outlives the arena is not a dangling pointer. It is a Java object that now refuses to work:
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class ClosedArenaDemo {
public static void main(String[] args) {
MemorySegment segment;
try (Arena arena = Arena.ofConfined()) {
segment = arena.allocate(16);
segment.set(ValueLayout.JAVA_INT, 0, 42);
System.out.println("alive inside: " + segment.scope().isAlive());
}
System.out.println("alive after: " + segment.scope().isAlive());
try {
segment.get(ValueLayout.JAVA_INT, 0);
} catch (IllegalStateException e) {
System.out.println("Access rejected: " + e.getMessage());
}
}
}segment.scope() returns a MemorySegment.Scope. Its isAlive() method reports whether the arena is still open. The failed read throws IllegalStateException.
Access from the wrong thread fails in a different way. Using a confined segment from a thread other than its owner throws WrongThreadException:
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class WrongThreadDemo {
public static void main(String[] args) throws InterruptedException {
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(16);
Thread other = new Thread(() -> {
try {
segment.get(ValueLayout.JAVA_INT, 0);
} catch (WrongThreadException e) {
System.out.println("Not the owner thread");
}
});
other.start();
other.join();
}
}
}Confined is the right default. Choose another type only when you can name the reason.
Shared arenas
A shared arena lets several threads access its segments, and any thread may close it. Use it when native memory is a buffer that worker threads fill or read in parallel.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class SharedDemo {
public static void main(String[] args) throws InterruptedException {
try (Arena arena = Arena.ofShared()) {
MemorySegment segment = arena.allocate(4 * 4L, 4);
Thread[] workers = new Thread[4];
for (int i = 0; i < workers.length; i++) {
final int index = i;
workers[i] = new Thread(() ->
segment.setAtIndex(ValueLayout.JAVA_INT, index, index * index));
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
for (int i = 0; i < 4; i++) {
System.out.println(segment.getAtIndex(ValueLayout.JAVA_INT, i));
}
}
}
}This prints 0, 1, 4 and 9. Each thread writes to its own element, so the program has no data race. Arenas protect lifetime only. They do not make reads and writes thread-safe, so you must still coordinate access to the same bytes.
Shared arenas cost more than confined ones at close time. Another thread might be in the middle of an access, so close() must make sure that no thread is using the memory before it frees it. That coordination is slower, and a program that creates and closes many short-lived shared arenas pays for it every time. If close() finds that a segment is being accessed, it throws IllegalStateException.
Auto and global arenas
An auto arena gives native memory the same lifetime behavior as a Java object. When the arena and all its segments become unreachable, the garbage collector frees the memory at some later point.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
public class AutoDemo {
public static void main(String[] args) {
Arena arena = Arena.ofAuto();
MemorySegment segment = arena.allocate(1024);
System.out.println(segment.byteSize());
try {
arena.close();
} catch (UnsupportedOperationException e) {
System.out.println("Auto arenas cannot be closed");
}
}
}The convenience has a cost. The collector tracks heap pressure, not native memory pressure. If a program allocates large native blocks and little heap, the collector may not run for a long time, and native memory can run out first. Auto arenas fit small, irregular allocations where deterministic cleanup is not worth the complexity.
The global arena never frees its memory. Use it for data that lives as long as the process, such as a lookup table loaded once at startup. Anything you allocate there stays until the JVM exits.
Choosing an arena
One arena per unit of work
The usual pattern is one arena per logical operation, opened in a try-with-resources block. Everything the operation needs is allocated there, and one close() frees it all. Here an arena holds three allocations of different sizes:
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class UnitOfWorkDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment header = arena.allocate(8);
MemorySegment payload = arena.allocate(256);
MemorySegment flags = arena.allocate(ValueLayout.JAVA_INT.byteSize(), 4);
System.out.println(header.byteSize() + payload.byteSize() + flags.byteSize());
}
}
}This prints 268. If the block exits through an exception, the arena is still closed, so the memory is not leaked.
An arena frees memory only as a group. If one segment is needed for a long time and others are needed briefly, put them in different arenas. Otherwise the short-lived memory stays allocated until the long-lived segment's arena closes.
A segment returned from a method must belong to an arena that outlives the call. If a method creates a confined arena, allocates from it, and closes it before returning, the caller receives a dead segment. A common fix is to accept an Arena or SegmentAllocator as a parameter, so the caller chooses the lifetime.
Common mistakes
- Using a segment after its arena closed. You get
IllegalStateException. Check the scope of the segment if you are unsure. - Handing a confined segment to another thread. You get
WrongThreadException. Use a shared arena, or copy the data. - Closing a confined arena from another thread. This also throws
WrongThreadException. - Expecting
close()to work onArena.ofAuto()orArena.global(). It throwsUnsupportedOperationException. - Keeping a raw address after the arena closes. Closing frees the memory, but native code still holding its address will read freed memory, and the API cannot detect that. Chapter 15 returns to this.
Exercise
A worker thread creates a segment from Arena.ofConfined() and passes it to a thread pool, where several tasks read from it. What exception do the tasks get, and which arena type fixes the problem if the memory must be freed deterministically?
Show answer
Each task running on a thread other than the creator gets WrongThreadException, because a confined arena allows access only from its owner thread. Arena.ofShared() fixes this, since any thread may access its segments and close it. The program must still ensure that all tasks finish before the arena is closed.
Exercise
What does the following code print, and why? Arena arena = Arena.ofConfined(); MemorySegment s = arena.allocate(8); arena.close(); System.out.println(s.scope().isAlive());
Show answer
It prints false. Closing the arena frees its memory and marks its scope as no longer alive. The segment object still exists, but any read or write through it would throw IllegalStateException. Calling isAlive() is safe.