Sub topic 2
Memory segments: bounded views of native memory
This chapter assumes you know Java fundamentals and try-with-resources. It also assumes you have a JDK 22 or later installed. Arenas and layouts get their own chapters, so here you only need to use them in simple ways.
What a memory segment is
A MemorySegment is a view of a contiguous region of memory. It has three properties:
- Address: where the region starts.
- Size: how many bytes it covers, readable with
byteSize(). - Lifetime: how long the memory stays valid.
C gives you a raw pointer with no size. A segment adds the size and the lifetime. Every read and write is checked against both. An access outside the bounds throws IndexOutOfBoundsException. An access after the memory is freed throws IllegalStateException. Neither one crashes the JVM.
Native and heap segments
A segment can point to two kinds of memory:
- Native segment: memory outside the Java heap. You usually get one from an
Arena, for examplearena.allocate(16, 4). This is the kind you pass to C. - Heap segment: a view over a Java array, created with
MemorySegment.ofArray(int[])and similar methods.isNative()returnsfalsefor it.
Both kinds use the same access methods. You can copy between them with copyFrom.
Reading and writing
You access a segment with a ValueLayout, which says how to interpret the bytes. The next chapters cover layouts in detail. Here, ValueLayout.JAVA_INT means a 4-byte int.
get(layout, offset)andset(layout, offset, value)take a byte offset.getAtIndex(layout, index)andsetAtIndex(layout, index, value)take an element index. The byte offset isindex * layout.byteSize().
Two more methods are worth knowing. asSlice(offset, size) returns a smaller segment over part of the original. It shares the same memory and the same lifetime. The slice also has its own bounds, so it can't reach outside its range.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class SegmentDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
// 16 bytes, aligned to 4 bytes so int access is valid
MemorySegment segment = arena.allocate(16, 4);
System.out.println(segment.byteSize()); // 16
System.out.println(segment.isNative()); // true
for (int i = 0; i < 4; i++) {
segment.setAtIndex(ValueLayout.JAVA_INT, i, i * 10);
}
// A slice covering bytes 8..15, which are elements 2 and 3
MemorySegment tail = segment.asSlice(8, 8);
System.out.println(tail.getAtIndex(ValueLayout.JAVA_INT, 0)); // 20
System.out.println(tail.getAtIndex(ValueLayout.JAVA_INT, 1)); // 30
try {
tail.get(ValueLayout.JAVA_INT, 8); // past the slice's end
} catch (IndexOutOfBoundsException e) {
System.out.println("Out of bounds");
}
// Copy a Java array into native memory
int[] data = {1, 2, 3, 4};
segment.copyFrom(MemorySegment.ofArray(data));
System.out.println(segment.getAtIndex(ValueLayout.JAVA_INT, 2)); // 3
}
}
}The tail.get(..., 8) call fails even though the underlying memory is still valid. The slice is only 8 bytes long, and offset 8 is just past its end.
Common errors
- Reading at the wrong offset.
gettakes bytes andgetAtIndextakes elements. Mixing them up reads the wrong data without any error, as long as the result stays in bounds. - Misaligned access. Reading a
JAVA_INTat an address that is not a multiple of 4 throwsIllegalArgumentException. Ask for alignment when you allocate, as the example does. - Using a segment after its memory is freed. The segment object stays in your variable, but any access throws
IllegalStateException. The arena chapter explains when memory is freed.
Exercise
A native segment is 24 bytes long. You call segment.getAtIndex(ValueLayout.JAVA_INT, 6). Does it succeed? Explain.
Show answer
No. Index 6 maps to byte offset 6 * 4 = 24, and a 4-byte read from offset 24 would need bytes 24 to 27. The segment ends at byte 23, so the call throws IndexOutOfBoundsException. The last valid index is 5.