Package java.lang.foreign


packagejava.lang.foreign

Provides low-level access to memory and functions outside the Java runtime.

Foreign memory access

The main abstraction introduced to support foreign memory access isMemorySegment, that models a contiguous region of memory, residing either inside or outside the Java heap. Memory segments are typically allocated using anArena, which controls the lifetime of the regions of memory backing the segments it allocates. The contents of a memory segment can be described using amemory layout, which provides basic operations to query sizes, offsets, and alignment constraints. Memory layouts also provide an alternate, more abstract way, toaccess memory segments usingvar handles, which can be computed usinglayout paths.

For example, to allocate an off-heap region of memory big enough to hold 10 values of the primitive typeint, and fill it with values ranging from0 to9, we can use the following code:

try (Arena arena = Arena.ofConfined()) {    MemorySegment segment = arena.allocate(10 * 4);    for (int i = 0 ; i < 10 ; i++) {        segment.setAtIndex(ValueLayout.JAVA_INT, i, i);    }}
This code creates anative memory segment, that is, a memory segment backed by off-heap memory; the size of the segment is 40 bytes, enough to store 10 values of the primitive typeint. The native segment is allocated using aconfined arena. As such, access to the native segment is restricted to the current thread (the thread that created the arena). Moreover, when the arena is closed, the native segment is invalidated, and its backing region of memory is deallocated. Note the use of thetry-with-resources construct: this idiom ensures that the off-heap region of memory backing the native segment will be released at the end of the block, according to the semantics described in Section14.20.3 ofThe Java Language Specification.

Memory segments provide strong safety guarantees when it comes to memory access. First, when accessing a memory segment, the access coordinates are validated (upon access), to make sure that access does not occur at any address that residesoutside the boundaries of the memory segment used by the access operation. We call this guaranteespatial safety; in other words, access to memory segments is bounds-checked, in the same way as array access is, as described in Section15.10.4 ofThe Java Language Specification.

Additionally, to prevent a region of memory from being accessedafter it has been deallocated (i.e.use-after-free), a segment is also validated (upon access) to make sure that the arena from which it has been obtained has not been closed. We call this guaranteetemporal safety.

Together, spatial and temporal safety ensure that each memory access operation either succeeds - and accesses a valid location within the region of memory backing the memory segment - or fails.

Foreign function access

The key abstractions introduced to support foreign function access areSymbolLookup,FunctionDescriptor andLinker. The first is used to look up symbols inside libraries; the second is used to model the signature of foreign functions, while the third is used to link foreign functions asMethodHandle instances, so that clients can perform foreign function calls directly in Java, without the need for intermediate layers of C/C++ code (as is the case with theJava Native Interface (JNI)).

For example, to compute the length of a string using the C standard library functionstrlen on a Linux/x64 platform, we can use the following code:

 Linker linker = Linker.nativeLinker(); SymbolLookup stdlib = linker.defaultLookup(); MethodHandle strlen = linker.downcallHandle(     stdlib.findOrThrow("strlen"),     FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS) ); try (Arena arena = Arena.ofConfined()) {     MemorySegment cString = arena.allocateFrom("Hello");     long len = (long)strlen.invokeExact(cString); // 5 }
Here, we obtain anative linker and we use it tolook up thestrlen function in the standard C library; adowncall method handle targeting said function is subsequentlyobtainedRESTRICTED. To complete the linking successfully, we must provide aFunctionDescriptor instance, describing the signature of thestrlen function. From this information, the linker will uniquely determine the sequence of steps which will turn the method handle invocation (here performed usingMethodHandle.invokeExact(java.lang.Object...)) into a foreign function call, according to the rules specified by the ABI of the underlying platform.

TheArena class also provides many useful methods for interacting with foreign code, such asconverting Java strings into zero-terminated, UTF-8 strings, as demonstrated in the above example.

API Note:
Usual memory model guarantees (see17.4) do not apply when accessing native memory segments as these segments are backed by off-heap regions of memory.
Since:
22
External Specifications