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.
kvi5hnuCode Sprout team member18 min readOn this page
The previous article read and wrote native memory with plain byte offsets: segment.get(JAVA_INT, 12). That works, but real C data comes in structs, arrays of structs and unions, and computing offsets by hand is tedious and fragile. A wrong offset is silently wrong, and C adds invisible padding that is easy to forget. Memory layouts describe the shape of native data in Java. From a layout the API computes sizes, offsets and alignment, checks them, and produces var handles that read and write a named member directly.
The layout family
MemoryLayout is a sealed interface with a small hierarchy:
ValueLayout: a single value of a Java primitive type, or an address. Its constants includeJAVA_BYTE,JAVA_SHORT,JAVA_CHAR,JAVA_INT,JAVA_LONG,JAVA_FLOAT,JAVA_DOUBLE,JAVA_BOOLEANandADDRESS. Subinterfaces such asValueLayout.OfIntandAddressLayoutgive each one a precise type.GroupLayout: a layout made of member layouts. AStructLayoutplaces its members one after another; aUnionLayoutplaces all of them at offset 0.SequenceLayout: a fixed number of repetitions of one element layout, like a C array.PaddingLayout: unused bytes, which exist only to keep later members aligned.
Every layout has a size (byteSize()), an alignment (byteAlignment()), and an optional name. Layouts are immutable values. Methods such as withName, withoutName and withByteAlignment return modified copies, and two layouts with the same structure are equals.
Value layouts
A value layout has a carrier type (the Java type its values are read as), a byte order, a size and an alignment. The toString form is compact. i4 is a 4-byte int, j8 is a long, a8 is an address, and z1 is a boolean. An uppercase letter means big-endian, and a prefix such as 1% shows an alignment different from the size. The _UNALIGNED variants, for example JAVA_INT_UNALIGNED, have alignment 1 for data that is packed without gaps.
withOrder(ByteOrder.BIG_ENDIAN) creates a layout for network or file formats in big-endian order. withName("count") attaches a name, which group layouts use to select members.
C types and canonical layouts
C does not fix the size of its types. A long is 8 bytes on 64-bit Linux and macOS but 4 bytes on 64-bit Windows, and wchar_t is 4 bytes on Linux and macOS but 2 on Windows. A layout that is meant to mirror a C declaration should not hard-code JAVA_LONG for a C long. Linker.nativeLinker().canonicalLayouts() returns a map from C type names ("bool", "char", "short", "int", "float", "long", "long long", "double", "void*", "size_t", "wchar_t") to the layout that type has on the current platform:
MemoryLayout cLong = Linker.nativeLinker().canonicalLayouts().get("long");
The int, float, double, short and char types (the C char is one byte, so it maps to JAVA_BYTE, never JAVA_CHAR) are the same on all mainstream 64-bit platforms. Only the types whose sizes vary need this lookup. The jextract tool, described in the next article, uses exactly this approach to generate platform-specific layouts from header files.
Struct layouts
Consider the struct that the libsndfile audio library fills with information about a sound file:
typedef struct SF_INFO {
sf_count_t frames; /* a 64-bit integer */
int samplerate;
int channels;
int format;
int sections;
int seekable;
} SF_INFO;
The corresponding layout lists the members in order and gives each one a name:
static final StructLayout SF_INFO = MemoryLayout.structLayout(
JAVA_LONG.withName("frames"),
JAVA_INT.withName("samplerate"),
JAVA_INT.withName("channels"),
JAVA_INT.withName("format"),
JAVA_INT.withName("sections"),
JAVA_INT.withName("seekable"),
MemoryLayout.paddingLayout(4)).withName("SF_INFO");
The final paddingLayout(4) is easy to miss and important. The members themselves occupy 8 + 5 × 4 = 28 bytes. The struct contains a long, so its alignment is 8, and C rounds the size of every struct up to a multiple of its alignment. That way each element of an array of these structs starts at a properly aligned address. sizeof(SF_INFO) is therefore 32. Without the trailing padding the Java layout would have size 28. Native code would then write 32 bytes into a 28-byte segment, or an array of these structs would have its elements at the wrong addresses.
The struct's alignment is the largest alignment of its members. byteOffset reports where a member lives, and memberLayouts() lists the members, padding included.
Alignment and padding
The FFM API does not insert padding by itself; it only checks it. Every member in a struct layout must sit at an offset that is a multiple of its alignment. If it does not, structLayout throws IllegalArgumentException ("Invalid alignment constraint for member layout"). The image shows the three ways to handle a struct whose members do not line up naturally.

- Mirror the C compiler. To match a C struct, add the same padding the C compiler adds: after
char tagcome 3 bytes, so thatvaluestarts at offset 4, and 3 trailing bytes round the size up to 12. - Packed data. File headers and network packets are often packed with no gaps. Use the
_UNALIGNEDvalue layouts there, which have alignment 1. - Reorder. In your own native code, ordering the members from the largest to the smallest alignment reduces padding. The reordered struct needs 8 bytes instead of 12.
withByteAlignment can raise a layout's alignment (for example to 16 for SIMD data), but it cannot lower a group's alignment below that of its members. A layout used as a sequence element must have a size that is a multiple of its alignment.
Layout paths
A layout path selects a nested layout. It is a series of MemoryLayout.PathElement values, usually imported statically:
groupElement("name")selects a struct or union member by name.groupElement(index)selects it by position.sequenceElement(i)selects elementiof a sequence.sequenceElement()selects an open element, whose index is supplied later as a coordinate of the var handle or method handle.sequenceElement(start, step)selects an open element with a stride. For examplesequenceElement(0, 2)covers the elements 0, 2, 4, ….dereferenceElement()follows a pointer (an address layout that has a target layout) into the memory it points to.
With a path, byteOffset(path...) computes an offset, and select(path...) returns the selected layout. An unknown member name or an index outside the sequence throws IllegalArgumentException. The path is checked when the offset or handle is created, not when memory is accessed. Paths for byteOffset must be fully specified, with no open elements.
long offset = SF_INFO.byteOffset(groupElement("channels")); // 12
int channels = info.get(JAVA_INT, offset);
Var handles from layouts
The more convenient approach asks the layout for a java.lang.invoke.VarHandle, the same class that is used for atomic field access in Java code:
static final VarHandle CHANNELS = SF_INFO.varHandle(groupElement("channels"));
...
CHANNELS.set(info, 0L, 2);
int channels = (int) CHANNELS.get(info, 0L);
The handle's coordinates are what you pass before the value. For a layout var handle they are the segment, then a long base offset, then one long index for each open sequence element in the path. The base offset says where in the segment the struct starts. Pass 0L when the segment is the struct itself, or i * SF_INFO.byteSize() to address a struct inside a larger block. This base-offset coordinate was added when the API became final in Java 22. Older code and books call handle.get(segment) without it, which now fails with WrongMethodTypeException.
Like all var handles, layout handles are signature-polymorphic. The values and the cast must match the exact types (int for JAVA_INT, long for the offset), so write 0L and not 0. Store the handles in static final fields. The JIT compiler then turns each access into a plain memory instruction with a bounds and liveness check.
Value layouts produce simpler handles of their own. JAVA_INT.varHandle() takes a segment and an offset. JAVA_FLOAT.arrayElementVarHandle() takes a segment, a base offset and an index, and treats the memory as an array of that value.
Unions
A union stores its members in the same bytes, so its size is the size of its largest member (rounded up to its alignment):
UnionLayout union = MemoryLayout.unionLayout(JAVA_INT.withName("bits"), JAVA_FLOAT.withName("value"));
Var handles for the members all use offset 0. Writing value and reading bits reinterprets the float's bytes, just as a C union does, and gives the same result as Float.floatToRawIntBits. Native APIs use unions for variant records, such as the event structures in windowing systems, where a tag field tells which member is valid.
Sequence layouts
MemoryLayout.sequenceLayout(count, element) describes a fixed-size array. Its size is count × element.byteSize(), and it can contain structs, which gives an array of structs:
SequenceLayout points = MemoryLayout.sequenceLayout(4, POINT); // struct Point { float x, y; } points[4];
VarHandle x = points.varHandle(sequenceElement(), groupElement("x"));
x.set(segment, 0L, 2L, 1.5f); // points[2].x = 1.5f
The open sequenceElement() adds an index coordinate. The handle checks it against the element count, so index 4 in a Point[4] throws IndexOutOfBoundsException instead of writing past the array. Other useful methods:
elementCount()andelementLayout()describe the sequence;withElementCount(n)changes the count.flatten()turns nested sequences into one: a[3:[4:i4]]becomes[12:i4].reshape(2, -1)turns[12:i4]into[2:[6:i4]], where-1means "infer this dimension".segment.elements(layout)streams the elements as slices, andsegment.toArray(JAVA_FLOAT)copies a whole region into a Java array.
The pre-final API had sequences with an unspecified length. These no longer exist: the count is always given, and it cannot be negative.
Offset, slice and scale handles
Three layout methods return MethodHandles for computations that depend on runtime indexes:
byteOffsetHandle(path...)computes the offset of a path with open elements. Its parameters are a base offset and the indexes, and it returns along.sliceHandle(path...)returns a slice of a segment for the selected layout. Its parameters are the segment, a base offset and the indexes. It is the tool for nested structs: the result is a small segment that covers justlines[i].from, for example, and can be passed to code that expects aPoint.scaleHandle()computesoffset + index × byteSize(), which is the address arithmetic for an array of this layout.
These handles are called with invokeExact, so the argument and result types must be written exactly: (long) handle.invokeExact(0L, i) with long arguments.
Pointers and address layouts
C structs often contain pointers. A pointer member is an ADDRESS layout, which is 8 bytes with alignment 8 on 64-bit platforms. So in struct { int n; int *data; }, padding is needed after n exactly as for a long. Reading an address gives a MemorySegment whose address() is the pointer value and whose size is zero. The JVM cannot know how much memory lies behind a raw pointer, so it permits no access at all.
There are two ways to give the pointed-to memory a size:
segment.reinterpret(size)on the zero-length segment, orADDRESS.withTargetLayout(layout), an address layout that knows what it points to. Reading through it yields a segment of exactlylayout.byteSize()bytes. It also lets a path continue through the pointer withdereferenceElement(), as inouter.varHandle(groupElement("data"), dereferenceElement(), groupElement("count")).
Both are restricted methods. The size is a promise you make about native memory, and if it is wrong, Java code can read or corrupt memory it does not own. Like downcalls, they warn unless the module or class path is granted access with --enable-native-access=ALL-UNNAMED (or the module's name), and code can acknowledge the warning at compile time with @SuppressWarnings("restricted"). Pointers returned by native functions are discussed further in the next article.
Access modes
A layout var handle supports all the access modes of VarHandle, not just get and set:
getVolatile/setVolatile,getAcquire/setReleaseandgetOpaque/setOpaqueare memory-ordering variants with the same meaning as for Java fields.compareAndSet,compareAndExchangeandweakCompareAndSet...are atomic conditional updates.getAndSet,getAndAddand the bitwisegetAndBitwiseOr/And/Xorare atomic read-modify-write operations.
Not every mode is available for every layout (an unsupported one throws UnsupportedOperationException). Handles from _UNALIGNED layouts support only plain get and set. Volatile, acquire/release and opaque reads and writes work for every type. compareAndSet, compareAndExchange and getAndSet work for int, long, float, double and addresses (floating-point values are compared by their bit patterns), but not for byte, short, char or boolean. The numeric and bitwise getAndAdd/getAndBitwise... modes work for int, long and addresses. Together with a shared arena this gives lock-free counters and flags in native memory, including memory that is mapped from a file and shared with other processes.
Using structs with C functions
The following program passes and receives structs through two standard C library functions. div returns a div_t struct by value. A downcall handle for a function that returns a struct takes a SegmentAllocator as an extra first argument, and it allocates the returned struct there. gmtime returns a pointer to a static struct tm. The return type is declared as ADDRESS.withTargetLayout(TM), so the result is a segment with the size of the layout and can be read at once. Only the first nine members of struct tm are standard, and some C libraries append more, so the layout covers just those nine members. That is safe because the program only reads through it. The Linker calls are covered in detail in the next article.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
public class CStructs {
// typedef struct { int quot; int rem; } div_t;
static final StructLayout DIV_T = MemoryLayout.structLayout(
JAVA_INT.withName("quot"), JAVA_INT.withName("rem"));
// The first nine members of struct tm are the same on every platform; some C libraries add more.
static final StructLayout TM = MemoryLayout.structLayout(
JAVA_INT.withName("tm_sec"), JAVA_INT.withName("tm_min"), JAVA_INT.withName("tm_hour"),
JAVA_INT.withName("tm_mday"), JAVA_INT.withName("tm_mon"), JAVA_INT.withName("tm_year"),
JAVA_INT.withName("tm_wday"), JAVA_INT.withName("tm_yday"), JAVA_INT.withName("tm_isdst"));
static final VarHandle QUOT = DIV_T.varHandle(groupElement("quot"));
static final VarHandle REM = DIV_T.varHandle(groupElement("rem"));
static int tm(MemorySegment tm, String field) {
return tm.get(JAVA_INT, TM.byteOffset(groupElement(field)));
}
@SuppressWarnings("restricted")
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
SymbolLookup libc = linker.defaultLookup();
// div_t div(int numerator, int denominator): returns a struct by value
MethodHandle div = linker.downcallHandle(libc.findOrThrow("div"),
FunctionDescriptor.of(DIV_T, JAVA_INT, JAVA_INT));
// struct tm *gmtime(const time_t *timer): returns a pointer to a static struct
MethodHandle gmtime = linker.downcallHandle(libc.findOrThrow("gmtime"),
FunctionDescriptor.of(ADDRESS.withTargetLayout(TM), ADDRESS));
try (Arena arena = Arena.ofConfined()) {
// the first argument of a struct-returning handle allocates the result
var result = (MemorySegment) div.invokeExact((SegmentAllocator) arena, 17, 5);
System.out.println("div(17, 5): quot " + (int) QUOT.get(result, 0L) + ", rem " + (int) REM.get(result, 0L));
MemorySegment time = arena.allocateFrom(JAVA_LONG, 1_000_000_000L); // time_t is 64 bits
var tm = (MemorySegment) gmtime.invokeExact(time); // sized by the target layout
System.out.printf("gmtime(1000000000): %04d-%02d-%02d %02d:%02d:%02d UTC, weekday %d, day of year %d%n",
tm(tm, "tm_year") + 1900, tm(tm, "tm_mon") + 1, tm(tm, "tm_mday"),
tm(tm, "tm_hour"), tm(tm, "tm_min"), tm(tm, "tm_sec"), tm(tm, "tm_wday"), tm(tm, "tm_yday") + 1);
System.out.println("struct tm seen through the layout: " + tm.byteSize() + " bytes");
}
}
}
Run it with java --enable-native-access=ALL-UNNAMED CStructs.java. Without the option, the restricted calls still work but print a warning. Output on macOS and Linux:
div(17, 5): quot 3, rem 2
gmtime(1000000000): 2001-09-09 01:46:40 UTC, weekday 0, day of year 252
struct tm seen through the layout: 36 bytes
The billionth second of the Unix epoch fell on a Sunday (weekday 0). gmtime returns a pointer to a buffer shared by later calls, and it is not thread-safe. Multithreaded C code uses gmtime_r (POSIX) or gmtime_s (Windows). On Windows, gmtime may not be exported under that name by the C runtime, which is a reminder that symbol names, like type sizes, are platform details.
The program
The demo uses only layouts and memory access, which are not restricted. It prints value layouts and the C type sizes of the current platform, builds the SF_INFO struct, shows the three padding strategies, a union, an array of structs with open indexes, nested structs with offset and slice handles, and an atomic counter shared by four threads.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.MemoryLayout.PathElement.sequenceElement;
import static java.lang.foreign.ValueLayout.*;
public class Solution {
// struct SF_INFO { long long frames; int samplerate; int channels; int format; int sections; int seekable; };
static final StructLayout SF_INFO = MemoryLayout.structLayout(
JAVA_LONG.withName("frames"),
JAVA_INT.withName("samplerate"),
JAVA_INT.withName("channels"),
JAVA_INT.withName("format"),
JAVA_INT.withName("sections"),
JAVA_INT.withName("seekable"),
MemoryLayout.paddingLayout(4)).withName("SF_INFO"); // C rounds the size up to 8-byte alignment
static final StructLayout POINT = MemoryLayout.structLayout(
JAVA_FLOAT.withName("x"), JAVA_FLOAT.withName("y")).withName("Point");
public static void main(String[] args) throws Throwable {
valueLayouts();
structs();
padding();
unions();
sequences();
nestedAndHandles();
atomics();
}
static void valueLayouts() {
System.out.println("== Value layouts ==");
for (ValueLayout v : List.of(JAVA_BYTE, JAVA_SHORT, JAVA_CHAR, JAVA_INT, JAVA_LONG, JAVA_FLOAT, JAVA_DOUBLE,
JAVA_BOOLEAN, ADDRESS, JAVA_INT_UNALIGNED))
System.out.printf(" %-6s carrier %-14s size %d, alignment %d%n", v, v.carrier().getSimpleName(),
v.byteSize(), v.byteAlignment());
System.out.println("JAVA_INT.withName(\"count\").withOrder(BIG_ENDIAN): "
+ JAVA_INT.withName("count").withOrder(java.nio.ByteOrder.BIG_ENDIAN));
Map<String, MemoryLayout> canonical = new TreeMap<>(Linker.nativeLinker().canonicalLayouts());
var sb = new StringBuilder("C types on this platform:");
for (String type : List.of("char", "short", "int", "long", "long long", "size_t", "wchar_t", "void*"))
sb.append(" ").append(type).append("=").append(canonical.get(type).byteSize());
System.out.println(sb);
}
static void structs() {
System.out.println();
System.out.println("== A struct layout ==");
System.out.println("layout " + SF_INFO + ", size " + SF_INFO.byteSize() + ", alignment " + SF_INFO.byteAlignment());
for (MemoryLayout member : SF_INFO.memberLayouts())
if (member.name().isPresent())
System.out.printf(" %-11s offset %2d%n", member.name().get(),
SF_INFO.byteOffset(groupElement(member.name().get())));
VarHandle frames = SF_INFO.varHandle(groupElement("frames"));
VarHandle channels = SF_INFO.varHandle(groupElement("channels"));
System.out.println("var handle coordinates: " + channels.coordinateTypes());
try (Arena arena = Arena.ofConfined()) {
MemorySegment info = arena.allocate(SF_INFO);
frames.set(info, 0L, 44_100L * 3); // the second coordinate: a base offset
channels.set(info, 0L, 2);
info.set(JAVA_INT, SF_INFO.byteOffset(groupElement("samplerate")), 44_100); // the offset way
System.out.println("frames " + (long) frames.get(info, 0L) + ", channels " + (int) channels.get(info, 0L)
+ ", samplerate " + info.get(JAVA_INT, 8));
}
try {
SF_INFO.byteOffset(groupElement("bitrate"));
} catch (IllegalArgumentException e) {
System.out.println("unknown member name: IllegalArgumentException");
}
}
static void padding() {
System.out.println();
System.out.println("== Alignment and padding: struct { char tag; int value; char flag; } ==");
try {
MemoryLayout.structLayout(JAVA_BYTE.withName("tag"), JAVA_INT.withName("value"));
} catch (IllegalArgumentException e) {
System.out.println("without padding: IllegalArgumentException: " + e.getMessage());
}
StructLayout padded = MemoryLayout.structLayout(
JAVA_BYTE.withName("tag"), MemoryLayout.paddingLayout(3),
JAVA_INT.withName("value"),
JAVA_BYTE.withName("flag"), MemoryLayout.paddingLayout(3));
System.out.println("as C lays it out: " + padded + ", size " + padded.byteSize()
+ ", value at offset " + padded.byteOffset(groupElement("value")));
StructLayout packed = MemoryLayout.structLayout(
JAVA_BYTE.withName("tag"), JAVA_INT_UNALIGNED.withName("value"), JAVA_BYTE.withName("flag"));
System.out.println("packed (as in a file format): " + packed + ", size " + packed.byteSize());
StructLayout reordered = MemoryLayout.structLayout(
JAVA_INT.withName("value"), JAVA_BYTE.withName("tag"), JAVA_BYTE.withName("flag"),
MemoryLayout.paddingLayout(2));
System.out.println("largest member first: size " + reordered.byteSize());
}
static void unions() {
System.out.println();
System.out.println("== A union: union { int bits; float value; } ==");
UnionLayout union = MemoryLayout.unionLayout(JAVA_INT.withName("bits"), JAVA_FLOAT.withName("value"));
VarHandle bits = union.varHandle(groupElement("bits"));
VarHandle value = union.varHandle(groupElement("value"));
try (Arena arena = Arena.ofConfined()) {
MemorySegment u = arena.allocate(union);
value.set(u, 0L, 1.0f);
System.out.println(union + ", size " + union.byteSize() + "; after value = 1.0f, bits = 0x"
+ Integer.toHexString((int) bits.get(u, 0L)) + " (Float.floatToIntBits: 0x"
+ Integer.toHexString(Float.floatToIntBits(1.0f)) + ")");
}
}
static void sequences() {
System.out.println();
System.out.println("== A sequence of structs: Point[4] ==");
SequenceLayout points = MemoryLayout.sequenceLayout(4, POINT);
System.out.println(points + ", size " + points.byteSize() + ", element count " + points.elementCount());
System.out.println("offset of points[2].y: " + points.byteOffset(sequenceElement(2), groupElement("y")));
VarHandle x = points.varHandle(sequenceElement(), groupElement("x")); // open element: an index coordinate
VarHandle y = points.varHandle(sequenceElement(), groupElement("y"));
System.out.println("coordinates with an open sequence element: " + x.coordinateTypes());
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(points);
for (long i = 0; i < 4; i++) {
x.set(segment, 0L, i, (float) i);
y.set(segment, 0L, i, (float) (i * i));
}
var sb = new StringBuilder("points:");
segment.elements(POINT).forEach(p -> sb.append(" (").append(p.get(JAVA_FLOAT, 0)).append(", ")
.append(p.get(JAVA_FLOAT, 4)).append(")"));
System.out.println(sb);
System.out.println("as a float[]: " + java.util.Arrays.toString(segment.toArray(JAVA_FLOAT)));
VarHandle element = JAVA_FLOAT.arrayElementVarHandle(); // segment, base offset, index
System.out.println("arrayElementVarHandle: float number 5 = " + (float) element.get(segment, 0L, 5L));
try {
x.get(segment, 0L, 4L);
} catch (IndexOutOfBoundsException e) {
System.out.println("index 4 in a Point[4]: IndexOutOfBoundsException");
}
}
}
static void nestedAndHandles() throws Throwable {
System.out.println();
System.out.println("== Nested structs and offset handles: struct Line { Point from; Point to; } ==");
StructLayout line = MemoryLayout.structLayout(POINT.withName("from"), POINT.withName("to")).withName("Line");
System.out.println(line + ", offset of to.y: " + line.byteOffset(groupElement("to"), groupElement("y")));
SequenceLayout lines = MemoryLayout.sequenceLayout(10, line);
MethodHandle offset = lines.byteOffsetHandle(sequenceElement(), groupElement("to"), groupElement("x"));
System.out.println("byteOffsetHandle for lines[i].to.x, i = 0..3:");
var sb = new StringBuilder(" ");
for (long i = 0; i < 4; i++) sb.append(" ").append((long) offset.invokeExact(0L, i));
System.out.println(sb);
MethodHandle slice = lines.sliceHandle(sequenceElement(), groupElement("from"));
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(lines);
MemorySegment from3 = (MemorySegment) slice.invokeExact(segment, 0L, 3L);
from3.set(JAVA_FLOAT, 4, 7.5f);
System.out.println("sliceHandle: lines[3].from is a " + from3.byteSize() + "-byte slice; after setting its y,"
+ " byte offset 52 holds " + segment.get(JAVA_FLOAT, 52));
}
}
static void atomics() throws InterruptedException {
System.out.println();
System.out.println("== Var handle access modes: an atomic counter in shared memory ==");
StructLayout stats = MemoryLayout.structLayout(JAVA_LONG.withName("hits"), JAVA_LONG.withName("misses"));
VarHandle hits = stats.varHandle(groupElement("hits"));
try (Arena arena = Arena.ofShared()) {
MemorySegment s = arena.allocate(stats);
Thread[] threads = new Thread[4];
for (int t = 0; t < threads.length; t++)
threads[t] = Thread.ofPlatform().start(() -> {
for (int i = 0; i < 10_000; i++) hits.getAndAdd(s, 0L, 1L); // atomic read-modify-write
});
for (Thread t : threads) t.join();
long total = (long) hits.getVolatile(s, 0L);
boolean swapped = hits.compareAndSet(s, 0L, 40_000L, 0L);
System.out.println("4 threads x 10000 getAndAdd: hits = " + total + "; compareAndSet(40000 -> 0) "
+ swapped + ", now " + (long) hits.getVolatile(s, 0L));
}
}
}
== Value layouts ==
b1 carrier byte size 1, alignment 1
s2 carrier short size 2, alignment 2
c2 carrier char size 2, alignment 2
i4 carrier int size 4, alignment 4
j8 carrier long size 8, alignment 8
f4 carrier float size 4, alignment 4
d8 carrier double size 8, alignment 8
z1 carrier boolean size 1, alignment 1
a8 carrier MemorySegment size 8, alignment 8
1%i4 carrier int size 4, alignment 1
JAVA_INT.withName("count").withOrder(BIG_ENDIAN): I4(count)
C types on this platform: char=1 short=2 int=4 long=8 long long=8 size_t=8 wchar_t=4 void*=8
== A struct layout ==
layout [j8(frames)i4(samplerate)i4(channels)i4(format)i4(sections)i4(seekable)x4](SF_INFO), size 32, alignment 8
frames offset 0
samplerate offset 8
channels offset 12
format offset 16
sections offset 20
seekable offset 24
var handle coordinates: [interface java.lang.foreign.MemorySegment, long]
frames 132300, channels 2, samplerate 44100
unknown member name: IllegalArgumentException
== Alignment and padding: struct { char tag; int value; char flag; } ==
without padding: IllegalArgumentException: Invalid alignment constraint for member layout: i4(value)
as C lays it out: [b1(tag)x3i4(value)b1(flag)x3], size 12, value at offset 4
packed (as in a file format): [b1(tag)1%i4(value)b1(flag)], size 6
largest member first: size 8
== A union: union { int bits; float value; } ==
[i4(bits)|f4(value)], size 4; after value = 1.0f, bits = 0x3f800000 (Float.floatToIntBits: 0x3f800000)
== A sequence of structs: Point[4] ==
[4:[f4(x)f4(y)](Point)], size 32, element count 4
offset of points[2].y: 20
coordinates with an open sequence element: [interface java.lang.foreign.MemorySegment, long, long]
points: (0.0, 0.0) (1.0, 1.0) (2.0, 4.0) (3.0, 9.0)
as a float[]: [0.0, 0.0, 1.0, 1.0, 2.0, 4.0, 3.0, 9.0]
arrayElementVarHandle: float number 5 = 4.0
index 4 in a Point[4]: IndexOutOfBoundsException
== Nested structs and offset handles: struct Line { Point from; Point to; } ==
[[f4(x)f4(y)](from)[f4(x)f4(y)](to)](Line), offset of to.y: 12
byteOffsetHandle for lines[i].to.x, i = 0..3:
8 24 40 56
sliceHandle: lines[3].from is a 8-byte slice; after setting its y, byte offset 52 holds 7.5
== Var handle access modes: an atomic counter in shared memory ==
4 threads x 10000 getAndAdd: hits = 40000; compareAndSet(40000 -> 0) true, now 0
Points to notice:
- The
toStringforms show the structure:x4is padding,|separates union members, and[4:...]is a sequence. The output came from macOS; on Windows the Clongwould print as 4 andwchar_tas 2. SF_INFOhas size 32 because of the trailing padding, and its members start at offsets 0, 8, 12, 16, 20 and 24.- The var handle coordinates are
MemorySegment, long, where thelongis the base offset. With an open sequence element, a secondlongis added for the index. - A struct of
charandintwithout padding was rejected when it was built, not when it was used. - Setting the union's float to 1.0 produced the IEEE 754 bit pattern
0x3f800000. - The four
Points, viewed as afloat[], are just eight floats in a row, so element 5 ispoints[2].y. - Each
Lineis 16 bytes, solines[i].to.xis at 8, 24, 40, 56. The slice forlines[3].fromstarts at 48, so itsyis at byte 52. - The 40,000
getAndAddcalls from four threads lost no updates, andcompareAndSetsucceeded because the expected value matched.
Common questions
How do I know the padding of a C struct?
Compute it from the C rules (each field aligned to its size), or let jextract generate the layout from the header. Check with the C compiler: printf("%zu %zu", sizeof(struct s), offsetof(struct s, field)). A StructLayout with wrong padding reads garbage silently.
Why does a VarHandle from a layout take an extra long argument?
Since Java 22, layout var handles always take a base offset after the segment, usually 0L, so the same handle can access a struct at any position. Pass it explicitly: handle.get(segment, 0L).
Can I use atomic operations on native memory?
Yes, on aligned access: volatile, acquire/release and opaque reads and writes work for every type; compareAndSet works for int, long, float, double and addresses; getAndAdd for int, long and addresses. Unaligned handles allow only plain get and set.
How do I work with an array of structs?
Use MemoryLayout.sequenceLayout(n, structLayout) and a path with sequenceElement() to get a handle that takes the index as an extra coordinate, or slice the segment with asSlice(i * struct.byteSize(), struct.byteSize()).
What's the easiest way to get all the layouts for a large C API?
Run jextract on the header. It generates Java classes with layouts, var handles and downcall handles for every struct and function, which you then use like a normal Java API.
API reference
| Class / method | Purpose |
|---|---|
ValueLayout.JAVA_BYTE ... JAVA_DOUBLE, JAVA_BOOLEAN, ADDRESS, JAVA_INT_UNALIGNED, ... | Layouts for single values. |
withName, withoutName, name(), withOrder, withByteAlignment | Modified copies of a layout. |
byteSize(), byteAlignment(), carrier() | Layout properties. |
Linker.nativeLinker().canonicalLayouts() | Platform layouts for C type names. |
MemoryLayout.structLayout, unionLayout, paddingLayout, sequenceLayout | Building composite layouts. |
GroupLayout.memberLayouts(), SequenceLayout.elementCount, elementLayout, withElementCount, flatten, reshape | Inspecting and reshaping layouts. |
PathElement.groupElement, sequenceElement(), sequenceElement(i), sequenceElement(start, step), dereferenceElement | Layout path elements. |
byteOffset(path...), select(path...) | Offset and layout of a path. |
varHandle(path...), ValueLayout.varHandle(), arrayElementVarHandle() | Var handles with segment, base offset and index coordinates. |
byteOffsetHandle, sliceHandle, scaleHandle | Method handles for offsets, slices and array arithmetic. |
AddressLayout.withTargetLayout, MemorySegment.reinterpret | Sizing memory behind a pointer (restricted). |
VarHandle.get, set, getVolatile, compareAndSet, getAndAdd, ... | Access modes. |
MemorySegment.elements(layout), toArray(layout) | Streaming and copying elements. |
Summary
- Memory layouts describe native data: value layouts for single values, struct and union layouts for groups, sequence layouts for arrays and padding layouts for gaps. Every layout has a size, an alignment and an optional name.
- C type sizes vary by platform; get them from
canonicalLayouts()instead of assuming a Clongis 8 bytes. - The API checks alignment but never adds padding. Add the padding the C compiler would insert, including the trailing padding that rounds a struct's size up to its alignment, or use unaligned layouts for packed data.
- Layout paths select members and elements;
byteOffsetcomputes offsets, andvarHandlecreates handles whose coordinates are the segment, alongbase offset (required since Java 22) and an index for each open sequence element. byteOffsetHandle,sliceHandleandscaleHandlecompute offsets and nested slices at run time. Pointers read as zero-length segments until they are sized with the restrictedwithTargetLayoutorreinterpret.- Var handles provide volatile, acquire/release and atomic access modes on native memory.
Practice Questions
1. A C struct is declared as struct { double x; int id; }. What layout describes it, and what is its size?
double has alignment 8 and occupies offsets 0 to 7; int follows at offset 8 with no gap. The members cover 12 bytes, but the struct's alignment is 8, so C rounds the size up to 16. The layout is MemoryLayout.structLayout(JAVA_DOUBLE.withName("x"), JAVA_INT.withName("id"), MemoryLayout.paddingLayout(4)), with size 16. Forgetting the trailing padding gives size 12, which places the second element of an array of these structs at the wrong address.
2. Code written for an older Java version calls HANDLE.get(segment) on a layout var handle and now fails. Why, and what is the fix?
Since the API became final in Java 22, var handles obtained from MemoryLayout.varHandle have an extra long coordinate after the segment: the base offset where the layout starts in the segment. The old call has the wrong number of coordinates and throws WrongMethodTypeException. Write HANDLE.get(segment, 0L), or pass the struct's offset when it sits inside a larger segment. The offset must be a long literal, because var handle invocations are matched on exact types.
3. How do you write a var handle that sets the y coordinate of the i-th point in an array of Point structs?
Build a sequence layout and use an open sequence element in the path: VarHandle y = MemoryLayout.sequenceLayout(n, POINT).varHandle(sequenceElement(), groupElement("y"));. Its coordinates are the segment, the base offset and the index, so y.set(segment, 0L, i, 2.5f) writes points[i].y, with i a long. The handle checks i against the element count. Alternatively, POINT.varHandle(groupElement("y")) with a base offset of i * POINT.byteSize() gives the same address without the count check.
4. A native function returns a pointer to a struct. Why can't the Java code read the struct directly, and what are the options?
The returned MemorySegment represents a raw address of size zero, because the JVM has no idea how large the memory behind it is or how long it lives, so every access is out of bounds. Declare the return type in the function descriptor as ADDRESS.withTargetLayout(STRUCT), which yields a segment of the struct's size, or call reinterpret(STRUCT.byteSize()) on the result (optionally with an arena to attach a lifetime). Both are restricted methods, because a wrong size would let Java code access memory it does not own.
5. When would you use a layout with JAVA_INT_UNALIGNED instead of adding padding?
When the bytes are defined by a format, not by a C compiler: file headers, network packets, or structs declared packed in C. There the fields follow each other with no gaps, and an int can start at any offset. JAVA_INT_UNALIGNED has alignment 1, so the struct layout accepts it at an odd offset, and access does not require an aligned address. Combine it with withOrder(ByteOrder.BIG_ENDIAN) for network byte order. Note that var handles from unaligned layouts support only plain get and set, not the volatile or atomic access modes.
Previous: Foreign Function and Memory API: Arenas and Memory Segments
Next: Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Related reading
- Java Pattern Matching: switch Patterns, Record Patterns and Guards
- Java Sealed Classes and Interfaces: Controlling Inheritance
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Variables, Constants, var and final Explained

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.
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.
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.