Sub topic 2
Memory segments: bounded views of native memory
This chapter assumes you know Java classes, static methods and try-with-resources. It also assumes you know basic C pointers and have JDK 22 or later installed. The Arena type appears in every example, but only as the thing that hands out memory. Arenas get their own chapter.
What a memory segment is
A MemorySegment is a Java object that describes a contiguous region of memory. It has three properties:
- Address. Where the region starts.
- Size. How many bytes it holds, returned by
byteSize(). - Lifetime. When the region stops being valid. An arena controls this.
A segment is not the memory itself. It is a checked view of it. Every read or write goes through the segment, and the runtime verifies that the access is inside the size and that the memory is still alive. A C pointer has neither check. If you read past the end of a C buffer, you get undefined behavior. If you do the same through a segment, you get a Java exception.
The two checks have names:
- Spatial bounds are the start address and size.
- Temporal bounds are the lifetime.
Native and heap segments
Segments come in two kinds.
| Kind | Backed by | Created with | `isNative()` |
|---|---|---|---|
| Native segment | Off-heap memory | `arena.allocate(...)` | `true` |
| Heap segment | A Java array on the heap | `MemorySegment.ofArray(...)` | `false` |
Both kinds have the same read and write methods, so code that processes a segment does not need to know which kind it has. The difference matters when you call C. Native code needs a stable address. The garbage collector can move a Java array, so you cannot give a heap segment's address to a C function. Pass native segments to native code.
Allocating, writing and reading
You get a native segment from an arena. Memory from Arena.allocate is zero-initialized. You read and write it by combining a ValueLayout with a byte offset. ValueLayout has its own chapter. For now, treat ValueLayout.JAVA_INT as "a 4-byte Java int".
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class SegmentBasics {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
// 16 bytes, aligned to 4 bytes, enough for four ints
MemorySegment seg = arena.allocate(16, 4);
System.out.println("size = " + seg.byteSize()); // 16
// setAtIndex multiplies the index by the layout size (4 bytes)
for (int i = 0; i < 4; i++) {
seg.setAtIndex(ValueLayout.JAVA_INT, i, i * 10);
}
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += seg.getAtIndex(ValueLayout.JAVA_INT, i);
}
System.out.println("sum = " + sum); // 60
// get and set take a byte offset instead of an index
System.out.println(seg.get(ValueLayout.JAVA_INT, 8)); // 20
try {
seg.get(ValueLayout.JAVA_INT, 16); // bytes 16..19 do not exist
} catch (IndexOutOfBoundsException e) {
System.out.println("caught out-of-bounds access");
}
}
}
}The two access styles are easy to confuse:
get(layout, offset)andset(layout, offset, value)take an offset in bytes.getAtIndex(layout, index)andsetAtIndex(layout, index, value)take an element index. The runtime multiplies the index by the layout's size.
Passing an element index to get is a common mistake. It does not fail, because get(JAVA_INT, 2) is a legal but misaligned read. It reads the wrong bytes.
Alignment
The second argument in arena.allocate(16, 4) is the alignment. An int layout such as ValueLayout.JAVA_INT requires the access address to be a multiple of 4. A misaligned access through it throws IllegalArgumentException. The unaligned variants, such as ValueLayout.JAVA_INT_UNALIGNED, allow any address. They suit packed binary formats where fields are not aligned.
Use arena.allocate(layout) when you have a layout. It uses the layout's size and alignment, so you cannot get them wrong.
Slices share memory
asSlice(offset, size) returns a new segment that covers part of the original. It does not copy anything. Writes through the slice appear in the parent. A slice also keeps the parent's lifetime, so it dies when the arena closes.
Slices are how you give a function access to part of a buffer without handing over all of it. MemorySegment.ofArray wraps a Java array without copying, and copyFrom copies bytes between segments.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.util.Arrays;
public class SliceDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(16, 4);
MemorySegment first = seg.asSlice(0, 8); // bytes 0..7
MemorySegment second = seg.asSlice(8); // bytes 8..15
first.fill((byte) 1); // every byte becomes 0x01
System.out.println(first.get(ValueLayout.JAVA_INT, 0)); // 16843009 (0x01010101)
MemorySegment heap = MemorySegment.ofArray(new int[] {7, 8});
System.out.println(heap.isNative() + " / " + seg.isNative()); // false / true
second.copyFrom(heap); // copies 8 bytes
// The writes through the slices are visible in the parent segment.
System.out.println(Arrays.toString(seg.toArray(ValueLayout.JAVA_INT)));
// [16843009, 16843009, 7, 8]
}
}
}toArray(layout) copies the segment's contents into a new Java array. Use it when you want a Java-side snapshot of native data. A slice's offset and size must fit inside the parent. Otherwise asSlice throws IndexOutOfBoundsException.
Segments can be read-only
asReadOnly() returns a view of the same memory that rejects writes with UnsupportedOperationException. Hand out a read-only view when a callee should only inspect the data.
Zero-length segments and `reinterpret`
When native code returns a pointer, or you read an ADDRESS value out of memory, Java has no way to know how much memory sits behind that address. The runtime therefore gives you a zero-length segment. Any read or write on it fails the bounds check.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class ZeroLengthDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment data = arena.allocate(16, 4);
data.set(ValueLayout.JAVA_INT, 0, 99);
MemorySegment slot = arena.allocate(ValueLayout.ADDRESS); // holds one pointer
slot.set(ValueLayout.ADDRESS, 0, data);
MemorySegment ptr = slot.get(ValueLayout.ADDRESS, 0);
System.out.println(ptr.byteSize()); // 0
MemorySegment sized = ptr.reinterpret(16); // restricted method
System.out.println(sized.get(ValueLayout.JAVA_INT, 0)); // 99
}
}
}reinterpret(newSize) returns a segment with the same address and a size you choose. It is a restricted method, because the runtime cannot verify that your size is true. Run this example with --enable-native-access=ALL-UNNAMED, or Java prints a warning. A later chapter covers restricted methods in detail.
Exceptions you will see
| Exception | Cause |
|---|---|
| `IndexOutOfBoundsException` | Offset plus access size falls outside the segment. |
| `IllegalStateException` | The arena has been closed, or a confined segment is used from another thread. |
| `IllegalArgumentException` | The access address is misaligned for the layout. |
| `UnsupportedOperationException` | A write to a read-only segment. |
These exceptions make segment bugs visible in testing. A bounds error that corrupts C memory may show up much later, far from the cause. A segment bounds error fails on the spot.
Exercise
A segment is allocated with arena.allocate(12, 4). Which of these calls on it throws, and which exception does each throw? (a) seg.get(ValueLayout.JAVA_INT, 8) (b) seg.getAtIndex(ValueLayout.JAVA_INT, 3) (c) seg.get(ValueLayout.JAVA_INT, 2)
Show answer
(a) does not throw. It reads bytes 8 to 11, the last int in the 12-byte segment. (b) throws IndexOutOfBoundsException. Index 3 means byte offset 12, which is past the end. (c) throws IllegalArgumentException, because offset 2 is not 4-byte aligned for JAVA_INT.
Exercise
You have a native segment buf of 64 bytes. You want a function to fill only the second half of it and must not let it touch the first half. Which call do you use, and does it copy the data?
Show answer
Use buf.asSlice(32, 32) and pass the result. It does not copy anything. The slice is a view of bytes 32 to 63, so writes through it appear in buf, and any access outside the slice fails the bounds check.