Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
kvi5hnuCode Sprout team member15 min readOn this page
The previous article showed how much ceremony JNI requires: C glue code for every function, compiled for every platform. The Foreign Function and Memory API (FFM), developed in Project Panama and final since Java 22 (JEP 454), does the same job from pure Java. It lives in the package java.lang.foreign and has two halves:
- Foreign memory: allocating, accessing and freeing memory outside the Java heap, safely, with bounds checks and well-defined lifetimes. It replaces
ByteBuffer.allocateDirectand the internalsun.misc.Unsafememory methods, whose removal is under way (JEP 471 deprecated them in Java 23, and JEP 498 makes them warn in Java 24). - Foreign functions: calling C functions in native libraries, and letting C call back into Java.
This article covers memory, after a first look at a function call. The next articles describe structured data with layouts, calling functions, and callbacks.
A first foreign call
The following program calls two functions of the C standard library: puts prints a string, and strlen counts its bytes.
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
MethodHandle strlen = linker.downcallHandle(stdlib.findOrThrow("strlen"),
FunctionDescriptor.of(JAVA_LONG, ADDRESS)); // size_t strlen(const char *s)
try (Arena arena = Arena.ofConfined()) {
MemorySegment greeting = arena.allocateFrom("Hello, Foreign World!");
long length = (long) strlen.invokeExact(greeting);
}
The pieces, each covered in detail later:
- The
Linkerknows the calling conventions of the platform: how arguments are passed in registers and on the stack. - A
SymbolLookupfinds the address of a function by name; the default lookup covers the C standard library. - A
FunctionDescriptordescribes the C signature: return type first, then parameter types.size_tis a 64-bit integer on 64-bit platforms, so it maps toJAVA_LONG; any pointer maps toADDRESS. downcallHandlecombines address and descriptor into aMethodHandle, which is called like any method handle.- The C function needs a C string, a zero-terminated byte array outside the Java heap. An
Arenaallocates it as aMemorySegmentand frees it when thetryblock ends.
Creating a downcall handle is a restricted method: done wrong, it can crash the JVM. Run such programs with java --enable-native-access=ALL-UNNAMED (or the module names), as described for JNI in the previous article. Without the option, the JVM prints a warning to standard error the first time, and a future release will refuse. javac -Xlint:restricted warns at compile time; annotate deliberate uses with @SuppressWarnings("restricted"). Everything else in this article, all of the memory API, is not restricted and needs no option.
Arenas
Native memory is not managed by the garbage collector. In C, every malloc needs a matching free; forgetting it leaks memory, and calling it twice or using memory after free corrupts the program. FFM makes this safe with arenas. An arena allocates memory segments and controls their lifetime: when an arena is closed, all its segments are freed at once, and from then on every access to them throws an exception instead of reading freed memory.

There are four kinds:
-
Arena.ofConfined(): segments can be used only by the thread that created the arena (its owner), which must also close it. This is the usual choice, with try-with-resources:javatry (Arena arena = Arena.ofConfined()) { MemorySegment buffer = arena.allocate(1024); ... } // freed hereAccess from another thread throws
WrongThreadException. The confinement makes access checks cheap and closing instantaneous. -
Arena.ofShared(): any thread may use the segments, and any thread may close the arena. Closing is more expensive, because the JVM must make sure no other thread is in the middle of an access (it performs a handshake with all threads). Use it when several threads work on the same native memory, and coordinate access yourself, as with any shared data. -
Arena.ofAuto(): any thread may use the segments, and the garbage collector frees them once the arena and all its segments are unreachable. It cannot be closed (closethrowsUnsupportedOperationException). Convenient, but like all GC-driven cleanup, you do not know when the memory is released, which matters for large allocations. -
Arena.global(): never freed. For memory needed for the whole run of the program.
Individual segments cannot be freed; only their arena can be closed. To free memory at different times, use different arenas. Arenas nest naturally: a long-lived arena for data that lives as long as a connection, a short one inside a method for temporary buffers.
Every segment knows its scope: segment.scope().isAlive() tells whether its arena is still open. The demo keeps a reference to a segment beyond the try block; accessing it afterwards throws IllegalStateException ("Already closed"). That is the core safety guarantee of FFM: Java code can never read freed native memory, a classic C bug.
Arena is an interface, so you can implement your own, for example an arena that hands out slices of one big block and is reset after each request. Arena extends SegmentAllocator, which is the interface with all the allocate methods.
Memory segments
A MemorySegment is a contiguous region of memory with a size (byteSize()). It is either
- native: off the Java heap, allocated by an arena (or by C code), with a fixed address that can be passed to C functions; or
- heap: backed by a Java array, created with
MemorySegment.ofArray(array). The garbage collector can move the array, so a heap segment has no stable address, and it normally cannot be passed to a native function.
isNative() tells which. All accesses are checked: against the bounds (IndexOutOfBoundsException), the liveness of the scope, the owner thread, and the alignment.
Allocating
MemorySegment raw = arena.allocate(100); // 100 bytes
MemorySegment aligned = arena.allocate(100, 16); // 100 bytes at an address divisible by 16
MemorySegment oneLong = arena.allocate(JAVA_LONG); // size and alignment from a layout
MemorySegment floats = arena.allocate(JAVA_FLOAT, 1000); // an array of 1000 floats
Memory allocated by an arena is filled with zeros. The ValueLayout constants (JAVA_BYTE, JAVA_SHORT, JAVA_CHAR, JAVA_INT, JAVA_LONG, JAVA_FLOAT, JAVA_DOUBLE, JAVA_BOOLEAN, ADDRESS) describe primitive values: their size, alignment and byte order. The next article covers layouts in depth; here they only tell the segment what type to read or write.
Reading and writing values
A segment does not remember what it contains. You state the type on every access:
segment.set(JAVA_INT, 0, 42); // layout, byte offset, value
int value = segment.get(JAVA_INT, 0);
segment.setAtIndex(JAVA_DOUBLE, 3, 2.5); // index in units of the layout size: offset 24
double d = segment.getAtIndex(JAVA_DOUBLE, 3);
get and set take a byte offset, getAtIndex and setAtIndex an element index that is multiplied by the size of the layout.
Two details from the demo:
- Alignment.
JAVA_INTrequires its offset (more precisely, the address) to be a multiple of 4,JAVA_LONGandJAVA_DOUBLEa multiple of 8, as most CPUs and C compilers expect. A misaligned access throwsIllegalArgumentException. For packed data, such as binary file formats, use the_UNALIGNEDvariants (JAVA_INT_UNALIGNED, ...). Heap segments are aligned only as much as their array's elements, so you cannot read alongfrom anint[]segment. - Byte order. The layouts use the platform's native order, which is little-endian on all mainstream processors (x64 and ARM64): the int
0x01020304is stored as04 03 02 01. For network protocols or file formats that store big-endian numbers, useJAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).
MemorySegment.NULL is a segment of size 0 at address 0, the C null pointer. Pointers returned from C functions arrive as such zero-length segments; to access the memory behind them, you must state its size with reinterpret, a restricted method, because the JVM cannot verify that the size is right. Article 109 shows this.
C strings
arena.allocateFrom(string) encodes a string as UTF-8, adds the terminating zero byte and returns the segment. The demo's "héllo" needs 7 bytes: é takes two bytes, and the terminator one. segment.getString(offset) reads a zero-terminated UTF-8 string back. Since Java 22, both methods also take a Charset, for C APIs that use other encodings, such as Windows' UTF-16 wide strings:
MemorySegment wide = arena.allocateFrom("hi", StandardCharsets.UTF_16LE); // 68 00 69 00 00 00
String back = wide.getString(0, StandardCharsets.UTF_16LE);
Note that a C function counts bytes, not characters: strlen reports 29 for the 28-character string in the listing, because ¡ takes two bytes in UTF-8.
Arrays
MemorySegment ints = arena.allocateFrom(JAVA_INT, 3, 1, 4, 1, 5); // or from an int[]
int third = ints.getAtIndex(JAVA_INT, 2);
int[] back = ints.toArray(JAVA_INT);
int sum = ints.elements(JAVA_INT).mapToInt(e -> e.get(JAVA_INT, 0)).sum();
allocateFrom copies a Java array (or varargs) into new native memory; toArray copies a segment into a new Java array; elements(layout) returns a stream of one-element slices.
Heap segments and buffers
MemorySegment.ofArray wraps any primitive array without copying; writes through the segment change the array. This gives arrays the same access API as native memory, which is useful for code that should work on both. A heap segment is not native, so heapBase() returns the array, and address() is only an offset within it.
FFM also interoperates with NIO buffers. MemorySegment.ofBuffer(buffer) views a ByteBuffer (a direct buffer gives a native segment), and segment.asByteBuffer() views a segment as a ByteBuffer for APIs that need one, such as channels. For heap segments this only works when the array is a byte[]. Segments improve on direct buffers in several ways: they can be larger than 2 GB (sizes are long), they are freed deterministically when their arena closes rather than by the garbage collector, and they support structured access with layouts.
Slices, copies and comparisons
asSlice(offset, size)returns a view of a part of a segment; it shares the memory, so writes through the slice are visible in the original. Slices are the natural way to hand out parts of a buffer.asReadOnly()returns a read-only view; writes through it throwIllegalArgumentException.fill(byte)sets every byte.MemorySegment.copy(source, sourceOffset, target, targetOffset, bytes)copies between segments (like C'smemmove, overlapping regions are handled correctly). Overloads copy between a segment and a Java array, converting element types:MemorySegment.copy(segment, JAVA_BYTE, offset, array, index, count).copyFrom(segment)copies a whole segment.mismatch(other)returns the offset of the first differing byte, or -1 if the segments are equal in content and size. Unlikeequals, which only checks that two segments start at the same address (in the same heap object), ignoring size, scope and read-only status, it compares contents.
Segment allocators
SegmentAllocator is the interface behind allocate and allocateFrom. Besides arenas, the JDK supplies two allocators that carve memory out of an existing segment, which is fast because nothing is allocated from the system:
SegmentAllocator.slicingAllocator(segment)hands out consecutive slices, respecting the alignment of each request, and throwsIndexOutOfBoundsExceptionwhen the segment is used up. In the demo, alongrequested after anintstarts at offset 8, not 4, because of its 8-byte alignment.SegmentAllocator.prefixAllocator(segment)always returns a slice starting at the beginning of the segment. Each allocation overwrites the previous one, which is what you want for a reusable scratch buffer.
Many FFM methods take a SegmentAllocator parameter, for example to allocate the memory for a struct returned by a C function, so you can choose how that memory is managed.
Memory-mapped files
FileChannel.map(mode, position, size, arena), added with FFM, maps a file into memory and returns a segment whose lifetime is tied to the arena: closing the arena unmaps the file. Unlike MappedByteBuffer, which is unmapped whenever the garbage collector gets around to it, this releases the mapping deterministically, and segments can map files larger than 2 GB. force() writes changes to the storage device, and load(), unload() and isLoaded() control whether the pages are in memory.
try (Arena arena = Arena.ofConfined();
FileChannel channel = FileChannel.open(path, READ, WRITE)) {
MemorySegment file = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size(), arena);
long count = file.get(JAVA_LONG, 0);
...
}
Hello, foreign world
This program completes the example from the beginning: it calls puts, fflush and strlen from the C library. All three take simple arguments, so the descriptors are short. puts writes through C's own output buffer, which is separate from System.out; calling fflush(NULL) makes the C output appear before the Java lines that follow.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
public class HelloForeign {
@SuppressWarnings("restricted") // downcallHandle is a restricted method
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker(); // the C calling conventions of this platform
SymbolLookup stdlib = linker.defaultLookup(); // the C standard library
// int puts(const char *s)
MethodHandle puts = linker.downcallHandle(stdlib.findOrThrow("puts"),
FunctionDescriptor.of(JAVA_INT, ADDRESS));
// size_t strlen(const char *s)
MethodHandle strlen = linker.downcallHandle(stdlib.findOrThrow("strlen"),
FunctionDescriptor.of(JAVA_LONG, ADDRESS));
// int fflush(FILE *stream): NULL flushes all output streams
MethodHandle fflush = linker.downcallHandle(stdlib.findOrThrow("fflush"),
FunctionDescriptor.of(JAVA_INT, ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment greeting = arena.allocateFrom("Hello, Foreign World! ¡Hola!");
int status = (int) puts.invokeExact(greeting);
int flushed = (int) fflush.invokeExact(MemorySegment.NULL); // C buffers its own output
long length = (long) strlen.invokeExact(greeting);
System.out.println("puts returned " + status + ", fflush " + flushed);
System.out.println("strlen counts UTF-8 bytes: " + length + "; the Java string has "
+ "Hello, Foreign World! ¡Hola!".length() + " chars");
} // the C string is freed here
}
}
Compile and run it with native access enabled:
javac HelloForeign.java
java --enable-native-access=ALL-UNNAMED HelloForeign
Output on macOS (the value puts returns is only specified to be non-negative on success, so it differs between C libraries):
Hello, Foreign World! ¡Hola!
puts returned 10, fflush 0
strlen counts UTF-8 bytes: 29; the Java string has 28 chars
No C compiler, no header, no library of your own: the method handles call straight into the existing C library.
The program
The demo uses only the memory half of the API, which is not restricted, so it runs without any command-line option. It exercises the four arena kinds, value access, strings and arrays, heap segments, slices, allocators and a mapped temporary file.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SegmentAllocator;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.HexFormat;
import static java.lang.foreign.ValueLayout.*;
public class Solution {
public static void main(String[] args) throws Exception {
arenas();
accessing();
stringsAndArrays();
heapSegments();
slicesAndCopies();
allocators();
mappedFile();
}
static String hex(MemorySegment s) {
return HexFormat.ofDelimiter(" ").formatHex(s.toArray(JAVA_BYTE));
}
static void arenas() throws InterruptedException {
System.out.println("== Arenas control the lifetime of native memory ==");
MemorySegment escaped;
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(16);
System.out.println("confined segment: " + segment.byteSize() + " bytes, native " + segment.isNative()
+ ", alive " + segment.scope().isAlive() + ", zero-filled " + (segment.get(JAVA_LONG, 8) == 0));
segment.set(JAVA_INT, 0, 42);
Thread other = Thread.ofPlatform().start(() -> {
try {
segment.get(JAVA_INT, 0);
} catch (WrongThreadException e) {
System.out.println("access from another thread: WrongThreadException");
}
});
other.join();
escaped = segment;
} // close() frees the memory
System.out.println("after close: alive " + escaped.scope().isAlive());
try {
escaped.get(JAVA_INT, 0);
} catch (IllegalStateException e) {
System.out.println("access after close: IllegalStateException: " + e.getMessage());
}
try (Arena shared = Arena.ofShared()) {
MemorySegment counter = shared.allocate(JAVA_LONG);
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++)
threads[i] = Thread.ofPlatform().start(() -> {
synchronized (Solution.class) { counter.set(JAVA_LONG, 0, counter.get(JAVA_LONG, 0) + 1); }
});
for (Thread t : threads) t.join();
System.out.println("shared arena, 4 threads incremented a counter: " + counter.get(JAVA_LONG, 0));
}
MemorySegment auto = Arena.ofAuto().allocate(8); // freed by the GC when unreachable
System.out.println("automatic arena segment alive: " + auto.scope().isAlive());
try {
Arena.global().close();
} catch (UnsupportedOperationException e) {
System.out.println("the global arena cannot be closed: UnsupportedOperationException");
}
}
static void accessing() {
System.out.println();
System.out.println("== Reading and writing values ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment s = arena.allocate(16, 8); // 16 bytes, 8-byte aligned
s.set(JAVA_INT, 0, 0x01020304);
s.set(JAVA_SHORT, 4, (short) -2);
s.set(JAVA_BYTE, 6, (byte) 'J');
s.set(JAVA_DOUBLE, 8, 1.5);
System.out.println("bytes: " + hex(s));
System.out.println("native byte order " + ByteOrder.nativeOrder() + "; the int read big-endian: "
+ Integer.toHexString(s.get(JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN), 0)));
System.out.println("values: " + Integer.toHexString(s.get(JAVA_INT, 0)) + ", " + s.get(JAVA_SHORT, 4)
+ ", " + (char) s.get(JAVA_BYTE, 6) + ", " + s.get(JAVA_DOUBLE, 8));
try {
s.get(JAVA_INT, 1); // JAVA_INT requires 4-byte alignment
} catch (IllegalArgumentException e) {
System.out.println("int at offset 1: IllegalArgumentException (misaligned); "
+ "JAVA_INT_UNALIGNED reads " + Integer.toHexString(s.get(JAVA_INT_UNALIGNED, 1)));
}
try {
s.get(JAVA_LONG, 16);
} catch (IndexOutOfBoundsException e) {
System.out.println("long at offset 16 of a 16-byte segment: IndexOutOfBoundsException");
}
System.out.println("MemorySegment.NULL: address " + MemorySegment.NULL.address() + ", size "
+ MemorySegment.NULL.byteSize());
}
}
static void stringsAndArrays() {
System.out.println();
System.out.println("== C strings and arrays ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment cString = arena.allocateFrom("héllo");
System.out.println("allocateFrom(\"héllo\"): " + cString.byteSize() + " bytes: " + hex(cString)
+ " -> getString: " + cString.getString(0));
MemorySegment wide = arena.allocateFrom("hi", StandardCharsets.UTF_16LE);
System.out.println("UTF-16LE \"hi\": " + hex(wide) + " -> " + wide.getString(0, StandardCharsets.UTF_16LE));
MemorySegment ints = arena.allocateFrom(JAVA_INT, 3, 1, 4, 1, 5, 9, 2, 6);
System.out.println("int array: " + ints.byteSize() + " bytes, element 5 = " + ints.getAtIndex(JAVA_INT, 5));
ints.setAtIndex(JAVA_INT, 0, 30);
int sum = ints.elements(JAVA_INT).mapToInt(e -> e.get(JAVA_INT, 0)).sum();
System.out.println("after setAtIndex(0, 30): " + Arrays.toString(ints.toArray(JAVA_INT)) + ", sum " + sum);
MemorySegment floats = arena.allocate(JAVA_FLOAT, 4); // four zero floats
System.out.println("allocate(JAVA_FLOAT, 4): " + floats.byteSize() + " bytes, "
+ Arrays.toString(floats.toArray(JAVA_FLOAT)));
}
}
static void heapSegments() {
System.out.println();
System.out.println("== Heap segments wrap Java arrays ==");
int[] array = {10, 20, 30};
MemorySegment heap = MemorySegment.ofArray(array);
heap.setAtIndex(JAVA_INT, 1, 99);
System.out.println("ofArray(int[3]): " + heap.byteSize() + " bytes, native " + heap.isNative()
+ ", array after write: " + Arrays.toString(array) + ", heapBase present: " + heap.heapBase().isPresent());
ByteBuffer buffer = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder());
MemorySegment fromBuffer = MemorySegment.ofBuffer(buffer);
fromBuffer.set(JAVA_INT, 4, 7);
System.out.println("segment over a direct ByteBuffer: native " + fromBuffer.isNative()
+ ", buffer.getInt(4) = " + buffer.getInt(4));
try {
heap.asByteBuffer();
} catch (UnsupportedOperationException e) {
System.out.println("asByteBuffer of an int[] segment: UnsupportedOperationException (byte[] only)");
}
ByteBuffer view = MemorySegment.ofArray(new byte[] {1, 2, 3, 4}).asByteBuffer();
System.out.println("asByteBuffer of a byte[] segment: get(2) = " + view.get(2));
try {
heap.get(JAVA_LONG, 0);
} catch (IllegalArgumentException e) {
System.out.println("long from an int[] segment: IllegalArgumentException (int[] is only 4-byte aligned)");
}
}
static void slicesAndCopies() {
System.out.println();
System.out.println("== Slices, copies and comparisons ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment s = arena.allocate(8);
s.fill((byte) 0x11);
MemorySegment middle = s.asSlice(2, 4); // a view: shares the memory
middle.fill((byte) 0x22);
System.out.println("fill, then fill a slice(2, 4): " + hex(s));
MemorySegment readOnly = s.asReadOnly();
try {
readOnly.set(JAVA_BYTE, 0, (byte) 0);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
System.out.println("write to read-only view: " + e.getClass().getSimpleName());
}
MemorySegment copy = arena.allocate(8);
MemorySegment.copy(s, 0, copy, 0, 8);
copy.set(JAVA_BYTE, 6, (byte) 0x33);
System.out.println("copy changed at byte 6: mismatch = " + s.mismatch(copy)
+ ", identical slices mismatch = " + s.asSlice(0, 6).mismatch(copy.asSlice(0, 6)));
byte[] target = new byte[4];
MemorySegment.copy(s, JAVA_BYTE, 1, target, 0, 4);
System.out.println("copy bytes 1..4 into a Java array: " + HexFormat.ofDelimiter(" ").formatHex(target));
}
}
static void allocators() {
System.out.println();
System.out.println("== Segment allocators ==");
try (Arena arena = Arena.ofConfined()) {
MemorySegment block = arena.allocate(64, 8);
SegmentAllocator slicing = SegmentAllocator.slicingAllocator(block);
MemorySegment a = slicing.allocate(JAVA_INT);
MemorySegment b = slicing.allocate(JAVA_LONG); // aligned to 8: skips 4 bytes
MemorySegment c = slicing.allocateFrom("abc");
System.out.println("slicing allocator offsets in the block: " + (a.address() - block.address()) + ", "
+ (b.address() - block.address()) + ", " + (c.address() - block.address()));
try {
slicing.allocate(64);
} catch (IndexOutOfBoundsException e) {
System.out.println("block exhausted: IndexOutOfBoundsException");
}
SegmentAllocator prefix = SegmentAllocator.prefixAllocator(block);
MemorySegment p1 = prefix.allocate(JAVA_INT), p2 = prefix.allocate(JAVA_INT);
System.out.println("prefix allocator reuses the start: same address " + (p1.address() == p2.address()));
}
}
static void mappedFile() throws Exception {
System.out.println();
System.out.println("== A memory-mapped file as a segment ==");
Path file = Files.createTempFile("segment", ".txt");
try (Arena arena = Arena.ofConfined();
FileChannel channel = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
MemorySegment mapped = channel.map(FileChannel.MapMode.READ_WRITE, 0, 12, arena);
MemorySegment.copy("Hello, file!".getBytes(StandardCharsets.US_ASCII), 0, mapped, JAVA_BYTE, 0, 12);
mapped.force(); // write changes to the storage device
System.out.println("mapped segment: " + mapped.byteSize() + " bytes, isMapped() " + mapped.isMapped());
} // closing the arena unmaps the file
System.out.println("file content: " + Files.readString(file));
Files.delete(file);
}
}
== Arenas control the lifetime of native memory ==
confined segment: 16 bytes, native true, alive true, zero-filled true
access from another thread: WrongThreadException
after close: alive false
access after close: IllegalStateException: Already closed
shared arena, 4 threads incremented a counter: 4
automatic arena segment alive: true
the global arena cannot be closed: UnsupportedOperationException
== Reading and writing values ==
bytes: 04 03 02 01 fe ff 4a 00 00 00 00 00 00 00 f8 3f
native byte order LITTLE_ENDIAN; the int read big-endian: 4030201
values: 1020304, -2, J, 1.5
int at offset 1: IllegalArgumentException (misaligned); JAVA_INT_UNALIGNED reads fe010203
long at offset 16 of a 16-byte segment: IndexOutOfBoundsException
MemorySegment.NULL: address 0, size 0
== C strings and arrays ==
allocateFrom("héllo"): 7 bytes: 68 c3 a9 6c 6c 6f 00 -> getString: héllo
UTF-16LE "hi": 68 00 69 00 00 00 -> hi
int array: 32 bytes, element 5 = 9
after setAtIndex(0, 30): [30, 1, 4, 1, 5, 9, 2, 6], sum 58
allocate(JAVA_FLOAT, 4): 16 bytes, [0.0, 0.0, 0.0, 0.0]
== Heap segments wrap Java arrays ==
ofArray(int[3]): 12 bytes, native false, array after write: [10, 99, 30], heapBase present: true
segment over a direct ByteBuffer: native true, buffer.getInt(4) = 7
asByteBuffer of an int[] segment: UnsupportedOperationException (byte[] only)
asByteBuffer of a byte[] segment: get(2) = 3
long from an int[] segment: IllegalArgumentException (int[] is only 4-byte aligned)
== Slices, copies and comparisons ==
fill, then fill a slice(2, 4): 11 11 22 22 22 22 11 11
write to read-only view: IllegalArgumentException
copy changed at byte 6: mismatch = 6, identical slices mismatch = -1
copy bytes 1..4 into a Java array: 11 22 22 22
== Segment allocators ==
slicing allocator offsets in the block: 0, 8, 16
block exhausted: IndexOutOfBoundsException
prefix allocator reuses the start: same address true
== A memory-mapped file as a segment ==
mapped segment: 12 bytes, isMapped() true
file content: Hello, file!
Points to notice:
- The confined segment rejected another thread, and after the arena closed, the segment was dead: access threw
IllegalStateExceptioninstead of reading freed memory. - The int
0x01020304is stored little-endian,04 03 02 01; reading it big-endian gives0x04030201. The double 1.5 is3F F8 00 ...stored backwards. - The misaligned
intaccess failed, while the unaligned layout read the four bytes from offset 1. - The UTF-8 C string has 7 bytes for 5 characters, including the terminator; the UTF-16 one ends with two zero bytes.
- Writes through the heap segment changed the Java array itself.
- Filling the slice changed bytes 2 to 5 of the original segment.
- The slicing allocator placed the
longat offset 8 to keep it aligned. - The text written through the mapped segment was in the file after the arena unmapped it.
Common questions
Which arena should I use?
Arena.ofConfined() with try-with-resources for memory used by one thread within a scope: the common case. ofShared() when several threads use the memory. ofAuto() when the lifetime can't be scoped and the garbage collector may free it. global() for memory that lives as long as the program.
What happens if I access a segment after its arena is closed?
You get IllegalStateException: Already closed, not a crash. Accessing a confined segment from another thread throws WrongThreadException. These checks are what make FFM memory safe, in contrast to raw pointers.
How do I pass a Java string to C?
arena.allocateFrom(string) creates a null-terminated UTF-8 copy. Note that strlen then counts bytes: "héllo" is 6 bytes long. Read a C string back with segment.getString(0).
Is off-heap memory faster than arrays? Not by itself. Its benefits are size (beyond 2 GB, no GC pressure), deterministic freeing, sharing with native code and memory-mapped files. For ordinary computation, Java arrays are just as fast and simpler.
Do I need --enable-native-access for memory segments?
Not for allocating and using segments from arenas, which are safe operations. Only restricted methods need it: Linker downcalls and upcalls, SymbolLookup.libraryLookup, and MemorySegment.reinterpret.
API reference
| Class / method | Purpose |
|---|---|
Arena.ofConfined(), ofShared(), ofAuto(), global(), close() | Creating and closing arenas. |
SegmentAllocator.allocate(bytes), allocate(bytes, alignment), allocate(layout), allocate(layout, count) | Allocating zeroed native memory. |
allocateFrom(String), allocateFrom(String, Charset), allocateFrom(layout, values...) | Allocating and initializing. |
SegmentAllocator.slicingAllocator(segment), prefixAllocator(segment) | Allocators inside an existing segment. |
MemorySegment.byteSize, isNative, address, scope().isAlive(), heapBase, isReadOnly, NULL | Segment properties. |
get(layout, offset), set(layout, offset, value), getAtIndex, setAtIndex | Value access. |
getString(offset), getString(offset, charset), toArray(layout), elements(layout) | Reading strings and arrays. |
asSlice, asReadOnly, fill, copyFrom, MemorySegment.copy(...), mismatch | Views, copies and comparisons. |
MemorySegment.ofArray, ofBuffer, asByteBuffer | Heap segments and NIO buffers. |
FileChannel.map(mode, position, size, arena), force, load, isLoaded | Memory-mapped files. |
ValueLayout.JAVA_INT, ..., JAVA_INT_UNALIGNED, ..., ADDRESS, withOrder | Layouts for primitive values. |
Linker.nativeLinker, defaultLookup, downcallHandle, FunctionDescriptor.of | A first downcall (Article 109). |
--enable-native-access, @SuppressWarnings("restricted") | Permission for restricted methods. |
Summary
- The FFM API (
java.lang.foreign, final in Java 22) accesses native memory and calls native functions from pure Java. Restricted methods, such as creating downcall handles, require--enable-native-access. - Arenas own native memory: confined (one thread, closed explicitly, the default), shared (many threads), automatic (freed by the GC) and global (never freed). Closing an arena frees all its segments, and later access throws instead of corrupting memory.
- A
MemorySegmentis a bounds-checked region of native or heap memory. Access values with a layout and a byte offset or element index; mind alignment and byte order. allocateFromcreates C strings (UTF-8 with a terminator by default) and arrays;getStringandtoArrayread them back.- Slices share memory;
copy,fillandmismatchwork on whole regions; allocators carve slices out of existing segments;FileChannel.mapwith an arena maps files deterministically.
Practice Questions
1. Why can a confined arena be closed instantly, while closing a shared arena is more expensive?
Only the owner thread can access a confined arena's segments, and only that thread can close it, so at the moment of closing no other access can be in progress. With a shared arena, another thread could be in the middle of reading a segment when one thread closes the arena; freeing the memory then would let that thread read freed memory. The JVM therefore has to synchronize with all threads (a handshake) to make sure no access is in flight before the memory is released.
2. A method allocates a segment in a confined arena inside try-with-resources and returns it. What happens when the caller uses it?
The arena is closed when the try block ends, which frees the memory. The returned segment's scope is no longer alive, so the caller's first access throws IllegalStateException ("Already closed"). The method should instead receive an arena or SegmentAllocator from the caller, so that the caller controls the lifetime, or copy the data into a Java array before returning.
3. What does arena.allocateFrom("Grüße") produce, and how many bytes does it have?
A native segment with the UTF-8 encoding of the string plus a terminating zero byte, as C functions expect. ü and ß take two bytes each in UTF-8, so the five characters need 7 bytes, plus the terminator: 8 bytes. getString(0) decodes it back to "Grüße".
4. Why does segment.get(JAVA_LONG, 4) throw an exception on a freshly allocated segment, and how can a program read an 8-byte value from offset 4?
JAVA_LONG has an alignment of 8 bytes, and the address of offset 4 in an 8-byte aligned segment is not a multiple of 8, so the access is rejected with IllegalArgumentException. If the data really is stored at an unaligned position, as in many file formats and network packets, use JAVA_LONG_UNALIGNED, which has an alignment of 1 (and set the byte order with withOrder if the format is big-endian).
5. What advantages do memory segments have over direct ByteBuffers?
Segments are freed deterministically when their arena closes, while direct buffers are released only when the garbage collector finds them unreachable. Segment sizes and offsets are long, so segments can exceed 2 GB. Segments carry a lifetime and thread confinement that are checked on each access, so using freed memory is impossible. They support structured access with layouts and var handles. And segments can be passed directly to native functions through the FFM linker. asByteBuffer and ofBuffer connect the two where an API still needs buffers.
Previous: Native Methods with JNI: Calling C Code from Java
Next: FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Related reading
- Native Methods with JNI: Calling C Code from Java
- Printing in Java: Print Jobs, Multipage Printing and Print Services
- Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
- Java 2D Strokes, Paint, Transforms, Clipping and Transparency
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Native Methods with JNI: Calling C Code from Java
The Java Native Interface: declaring native methods, generating headers with javac -h, JNI function naming and type mapping, strings and modified UTF-8, arrays, calling Java from C, exceptions, references, building and loading libraries, native access restrictions, and why the FFM API replaces JNI.
Discussion
Sign in to ask a question or share what you learned.