Lesson · Foreign Function & Memory API
Arena and MemorySegment: a bounded view with an owner
12 min readArena & MemorySegments
The FFM API splits off-heap memory into two roles: a MemorySegment is the typed, bounded view you read and write, and an Arena is what owns the bytes and decides when they die. Getting an offset right is the easy half; getting the lifetime right is the half that ships bugs.
A segment is a claim on memory, with edges
A raw address says where a region starts and nothing else: not how far it goes, not how long it stays valid. MemorySegment exists to add exactly those two things. Every segment carries an address(), a byteSize(), and a scope(), and every access operation is checked against all three.
The address is not intended to be dereferenced by hand. For a native segment it is a real off-heap address; for a heap segment it is a virtualized offset into the Java heap (zero when the segment came from ofArray). Reads and writes go through a layout plus an offset, so the runtime can reject an out-of-bounds access before it touches memory.
There are several ways to get a segment, and the one you pick decides its lifetime.
| Factory | Backed by | Notes |
|---|---|---|
Arena.allocate | a fresh off-heap region | size and alignment you ask for; lifetime is the arena's |
Arena.allocateFrom | a region holding a value or a string | the usual way to build arguments and small records |
MemorySegment.ofArray(int[]) | a Java array on the heap | address is zero, accessible from any thread, lives as long as the array |
MemorySegment.ofBuffer(ByteBuffer) | the region behind a buffer | a direct buffer gives a native segment; a read-only buffer gives a read-only segment |
MemorySegment.ofAddress(long) | a raw address value | zero-length until you attach bounds; global scope |
FileChannel.map(mode, offset, size, arena) | a mapped file region | since JDK 22; lifetime is the arena's |
Spatial bounds catch offsets; temporal bounds catch time. A segment you cannot misuse or cannot outlive is the entire point of the API, so check both when you review a change.
The arena owns the memory
A segment is a view; something else must decide when the region is freed. That something is the Arena. Every segment obtained from an arena shares its scope, and closing the arena invalidates all of them at once, including slices of slices.
The factory you choose answers two questions at the same time: who may touch the memory, and how the lifetime ends.
| Arena | Access | How it ends |
|---|---|---|
ofConfined() | owner thread only; another thread gets WrongThreadException | close() by the owner; every segment dies with it |
ofShared() | any thread | close() from any thread, and it closes for all of them |
ofAuto() | any thread | the GC, once the arena and its segments are unreachable; close() throws UnsupportedOperationException |
global() | any thread | never; close() throws UnsupportedOperationException |
- Confined is the default choice. Single-threaded use gets the cheapest checks, and the confinement is enforced: access from another thread throws WrongThreadException, and so does closing from another thread.
- Close is not idempotent. Closing an already closed arena throws IllegalStateException by design, because a second close means the program lost track of the lifetime it promised to manage.
- After close, every segment from that arena is a landmine. Any read, write, slice, or copy throws IllegalStateException. The segment object still exists in your variables; the memory behind it does not.
- Automatic arenas hand the timing to the GC. They are convenient for long-lived caches, but the release moment is unspecified, so do not use one where a deadline matters.
- The global arena is a leak with better manners. Nothing is ever freed, which is only correct when the region truly lives for the process lifetime.
Put the arena in try-with-resources and let the compiler own the deadline. Every exit path, including the exceptional ones, reaches close().
Arena lifetime · block, string, slice
Every story with off-heap memory starts with the owner. Arena.ofConfined() creates an arena this thread owns, and it becomes the single gate for everything allocated through it.
One arena, three segments, one close. Real blocks are larger and the offsets differ; the lifetime rules do not change with size.
Layouts describe the bytes
Offsets work, but they do not say what is at the offset. A MemoryLayout describes the shape of a region, and from a layout you get two useful things: computed offsets, and var handles that perform typed access.
Layouts are built from leaves and combinations, and the names matter because layout paths refer to them.
| Layout kind | Example | What it describes |
|---|---|---|
| ValueLayout | JAVA_INT, JAVA_LONG, JAVA_DOUBLE, ADDRESS | a scalar; size and alignment come from the carrier (JAVA_INT aligns to 4, JAVA_LONG to ADDRESS.byteSize()), and byte order is native unless withOrder(...) is used |
| PaddingLayout | paddingLayout(4) | bytes to skip; explicit because structLayout never inserts alignment padding |
| SequenceLayout | sequenceLayout(count, element) | a homogeneous array; a count of zero models a C flexible array member |
| StructLayout | structLayout(...) | members in declaration order; withName(...) on each member is what makes PathElement.groupElement(name) work |
- C declares
struct Sample { int id; long value; };. On LP64 the long must start at an 8-byte offset, so 4 bytes of padding follow the int. - The layout:
structLayout(JAVA_INT.withName("id"), paddingLayout(4), JAVA_LONG.withName("value"))has a byte size of 16, andbyteOffset(groupElement("value"))returns 8. sample.varHandle(groupElement("value"))returns a VarHandle whose coordinates are (MemorySegment, long): the base offset you pass, plus the field offset the layout already knows.- Leave the padding out and structLayout rejects the layout on LP64: the long would land at offset 4, which its 8-byte alignment forbids. The padded layout describes the 64-bit ABI exactly, and would over-pad a 32-bit one, which is one more reason binding layouts come from a generator rather than from memory.
Describe the bytes once, then read them through the handle. The var handle also reports access modes such as get and set, plus the atomic ones; the ordering ladder for those belongs to the method handles lesson.
Structure · who owns what, and how the bytes are described
the arena is the deadline, the layout is the map
one owner, many segments
close() then any access: IllegalStateException, for every segment at once
a heap segment outside any arena: address is zero, any thread may read it, and it lives exactly as long as the array does
struct Sample · 16 bytes on LP64
structLayout does not insert padding. The four dashed bytes are written down because C puts them there, and every later member depends on them.
Strings and mapped files, the short version
Two conveniences cover most day-to-day work, and both are ordinary arena allocations underneath.
- Strings:
arena.allocateFrom(String)writes UTF-8 plus a terminating zero and returns the segment;segment.getString(0)reads up to that terminator;setString(offset, str)writes into a segment you already own, if it is big enough. - Mapped files:
FileChannel.map(MapMode.READ_WRITE, offset, size, arena)returns a segment whose lifetime is the arena's scope. A READ_ONLY mapping gives a read-only segment, andforce()pushes changes back to storage. - Slices narrow, they do not extend.
asSlice(offset, size)shares the region and inherits the scope, so a slice of a closed arena is exactly as dead as its parent.
A mapping is a segment, not a buffer. Layout access goes through the page cache, and closing the arena unmaps the region for every segment that came from it.
The ways a segment bites
Five failure modes account for nearly every FFM bug in production code, and none of them is exotic:
- The escape. A segment gets stored in a field, a cache, or a static map while its arena is a local variable. The block exits, the arena closes, and the stored segment becomes a landmine that detonates at some later, unrelated call site.
- The slice that outlives nothing. Slices inherit the parent's scope, so keeping a slice does not keep the memory alive. If the parent arena closes, the slice is invalid.
- The confined handoff. Passing a segment from a confined arena to another thread throws WrongThreadException even while the arena is healthy. If two threads really share the region, the arena must be shared.
- Alignment. A layout with a stricter alignment than the address supports fails the access. Heap segments cap the usable alignment by their element type, and
JAVA_LONG_UNALIGNEDis the escape hatch when foreign data is genuinely packed. - Endianness. Layout constants use native byte order. Foreign data does not have to, so a network-format field read with
JAVA_INTon a little-endian machine comes back byte-swapped unless the layout sayswithOrder(BIG_ENDIAN).
Reading a segment change in review
Use this sequence on any diff that touches off-heap memory. It is ordered by how expensive the mistake is.
- Find the arena factory. Confined, shared, automatic, or global: an unexplained choice here is the whole review.
- Trace every path out of the block. Anything that escapes must be either a copied Java value or a segment owned by an arena that demonstrably outlives the receiver.
- Look for segments in fields, caches, and long-lived collections, then ask which arena is alive at the moment they are read.
- For a confined arena, name the owner thread. Any other thread reaching the segment is WrongThreadException, not luck.
- For a mapped segment, check the MapMode and whether changes need
force()before the file is expected to see them. - For foreign data, check the byte order and whether the padding in the layout matches the C declaration it came from.
The arena is the answer to when; everything else is the answer to what. If a reviewer can name both, the change is probably safe.
The cached segment and the local arena
The classic failure: a lookup method opens `Arena.ofConfined()` in try-with-resources, allocates a segment, stores it in a cache or returns it in a wrapper, and closes the arena on the way out. The scope dies immediately, so every later read through that cached segment throws IllegalStateException, often minutes after the code that caused it has left the stack. Either the cache owns a long-lived arena, or the value copied out is a Java value. There is no third option that stays correct.
Interview angles
What does MemorySegment add on top of a raw address?+
Spatial and temporal bounds. The segment knows its byte size and its scope, and each access through a layout is checked against both, so an out-of-bounds offset throws instead of corrupting memory and a use-after-close throws instead of reading recycled pages.
Which Arena factory do you reach for, and why?+
ofConfined by default: single-threaded use gets the cheapest safety checks, and the confinement is enforced with WrongThreadException. Switch to ofShared when several threads touch the same region, and reserve ofAuto or global for lifetimes that really are GC-shaped or process-shaped.
What happens when you touch a segment after its arena closes?+
Any access operation throws IllegalStateException. The segment object survives as a Java object; the scope it points into is dead. Do not confuse that with WrongThreadException, which is about the calling thread rather than the lifetime.
Common misconception: The common wrong belief is that the runtime sets the segment to null or throws NullPointerException. Nothing nulls your variable: the object is still there, which is why the bug surfaces far from the close.
How do you model a C struct that has padding after an int?+
Declare the padding: structLayout(JAVA_INT.withName("id"), paddingLayout(4), JAVA_LONG.withName("value")) on LP64. structLayout does not insert alignment padding automatically, so a missing paddingLayout silently shifts every later member.
Follow-up: The next question is where the layout came from. In real projects it is generated from the header by jextract, which is the subject of the linker lesson.