Invoking the Java Compiler from Code: JavaCompiler, Tasks and Diagnostics
Running javac inside a Java program with the javax.tools Compiler API: JavaCompiler.run, compilation tasks, StandardJavaFileManager and locations, diagnostics, options like --release and -Werror, the JavacTask tree API, and in-process JDK tools via ToolProvider.
kvi5hnuCode Sprout team member10 min readOn this page
Many tools compile Java code while they run: IDEs, build tools, test frameworks, teaching platforms, template engines that turn pages into Java classes, and frameworks that generate code at run time. They do not start a separate javac process. Since Java 6 the compiler can be called as a library through the javax.tools API, which lets the caller supply the sources, decide where class files go, and receive errors and warnings as objects instead of text. This article covers compiling files and handling diagnostics. Article 78 compiles code held entirely in memory.
Getting the compiler
JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
The compiler lives in the jdk.compiler module. getSystemJavaCompiler returns null when it is missing, which happens in custom runtime images built with jlink that leave the module out (a full JDK always has it). Check for null, and if your application needs the compiler, include jdk.compiler in its image or add requires jdk.compiler to a modular application.
compiler.getSourceVersions() reports which language versions the compiler accepts, and SourceVersion.latest() is the newest one the running platform knows.
The simplest call: run
JavaCompiler extends the generic javax.tools.Tool interface, whose run method takes an input stream, an output stream, an error stream, and the command-line arguments:
int rc = compiler.run(null, out, err,
"-d", "classes", "-sourcepath", "src", "src/demo/Main.java");
A result of 0 means success. Passing null for the streams uses System.in, System.out and System.err. The arguments are exactly what you would pass to javac on the command line, so everything you know about javac options applies. The disadvantage is that errors come back as text in the error stream, which you would have to parse.
Compilation tasks
For real control, create a CompilationTask:
JavaCompiler.CompilationTask task = compiler.getTask(
out, // Writer for extra output; null means System.err
fileManager, // null means the standard file manager
listener, // DiagnosticListener; null means print to System.err
options, // Iterable<String>, e.g. List.of("-Xlint:all", "--release", "21")
classes, // class names for annotation processing, or null
units); // Iterable<? extends JavaFileObject> to compile
Boolean ok = task.call();

getTask only prepares the work; call() runs it once and returns true if there were no errors. CompilationTask implements Callable<Boolean>, so it can be submitted to an executor. Before calling, you can also use setLocale for the language of the messages, setProcessors to run specific annotation processors, and addModules for modular compilation.
The standard file manager
A JavaFileManager is the compiler's view of the file system. It finds sources and classes and writes the results. The standard one works with real files:
try (StandardJavaFileManager fm =
compiler.getStandardFileManager(listener, Locale.US, StandardCharsets.UTF_8)) {
fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, List.of(outDir));
Iterable<? extends JavaFileObject> units =
fm.getJavaFileObjectsFromPaths(List.of(Path.of("src/bad/Broken.java")));
compiler.getTask(null, fm, listener, List.of("-Xlint:all"), null, units).call();
}
The three arguments of getStandardFileManager are a listener for problems found while reading files, the locale for messages, and the charset of the source files (null means the platform default, UTF-8 since Java 18). The file manager should be closed when you are done, and it can be reused for several tasks, which saves time because it caches directory contents.
Locations tell the file manager where things are: SOURCE_PATH, CLASS_PATH, CLASS_OUTPUT, SOURCE_OUTPUT (for generated sources), ANNOTATION_PROCESSOR_PATH, PLATFORM_CLASS_PATH, MODULE_PATH, MODULE_SOURCE_PATH and others in StandardLocation. You can set them with setLocationFromPaths (Java 9) or with the equivalent command-line options (-d, -cp, -sourcepath). getJavaFileObjectsFromPaths(Collection<? extends Path>) (Java 13), getJavaFileObjects(Path...) and the older getJavaFileObjectsFromFiles and getJavaFileObjectsFromStrings turn files into compilation units.
Diagnostics
Every problem the compiler finds becomes a Diagnostic<? extends JavaFileObject>, delivered to a DiagnosticListener. The ready-made DiagnosticCollector simply stores them in a list:
var collector = new DiagnosticCollector<JavaFileObject>();
compiler.getTask(null, fm, collector, options, null, units).call();
for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
System.out.println(d.getKind() + " " + d.getLineNumber() + ": " + d.getMessage(Locale.US));
}
| Method | Returns |
|---|---|
getKind() | ERROR, WARNING, MANDATORY_WARNING, NOTE or OTHER |
getSource() | the JavaFileObject concerned, or null |
getLineNumber(), getColumnNumber() | 1-based position, or Diagnostic.NOPOS |
getPosition(), getStartPosition(), getEndPosition() | character offsets in the source, for highlighting |
getCode() | a stable key such as compiler.err.prob.found.req |
getMessage(Locale) | the human-readable text |
Use getCode() when a program has to react to specific problems: messages are localized and change between releases, codes do not. The start and end positions let an editor underline exactly the offending expression; for String s = 42; they cover 42.
Your own DiagnosticListener is a single method, so a lambda works: count problems, send them to a log, stop after the first error, or convert them into the format a build tool or IDE expects.
What the compiler reports depends on how far it gets. A syntax error stops compilation after parsing, so type errors in the same file only appear after the syntax is fixed. This matches the behaviour you know from the command line.
Useful options
Options are plain strings, the same as on the command line:
--release Ncompiles against the public API of Java N, so code that uses newer APIs is rejected. The demo compiles a call toIO.println, which only exists since Java 25: with--release 21the result iscompiler.err.cant.resolve.location, with--release 25it compiles. This is safer than-source/-target, which don't check APIs.-Xlint:all(or a selection like-Xlint:rawtypes,deprecation) enables warnings;-Werrorturns them into errors and makes the compilation fail.-proc:none,-proc:only,-proc:fullcontrol annotation processing. Since JDK 23, processors on the class path are no longer run unless you ask for them.-gfor full debug information,-parametersto keep method parameter names for reflection,-encodingfor non-UTF-8 sources.-Xmaxerrsand-Xmaxwarnslimit the number of reported problems.
Beyond compilation: the javac tree API
The object returned by getTask is, for the JDK's compiler, a com.sun.source.util.JavacTask. This class from the jdk.compiler module is a supported API (com.sun.source.* is exported, unlike com.sun.tools.javac.*) and splits compilation into steps:
JavacTask jt = (JavacTask) compiler.getTask(null, fm, null, null, null, units);
Iterable<? extends CompilationUnitTree> trees = jt.parse(); // syntax trees
jt.analyze(); // attribution and flow analysis
jt.generate(); // class files
You can walk the syntax trees with a TreeScanner or TreePathScanner, for example to find all method declarations and calls, which is the basis of linters, code metrics and refactoring tools. jt.addTaskListener reports when each phase starts and finishes for each class. Trees.instance(jt) connects trees to the javax.lang.model elements and types, so you can ask for the type of an expression after analyze().
For tools that only need to analyze code, stop after analyze() and generate nothing.
Running other JDK tools: java.util.spi.ToolProvider
javax.tools.ToolProvider is only for the compiler and a few related tools. Java 9 added a more general mechanism, java.util.spi.ToolProvider, through which command-line tools offer an in-process entry point:
ToolProvider jar = ToolProvider.findFirst("jar").orElseThrow();
int rc = jar.run(System.out, System.err,
"--create", "--file", "app.jar", "--main-class", "demo.Main", "-C", "classes", ".");
javac, jar, javap, javadoc, jlink, jmod, jdeps, jpackage and jnativescan are available this way. They take the same arguments as on the command line and write to the PrintWriters or PrintStreams you supply, which makes them easy to use in build scripts and tests.
The program
The demo creates three small packages in a temporary directory, compiles them with run and with tasks, loads and runs the result, prints the collected diagnostics for a file with deliberate mistakes, compares --release values and -Werror, walks syntax trees with JavacTask, and uses javap and jar through java.util.spi.ToolProvider. File names, not temporary paths, are printed so that the output is stable.
import com.sun.source.tree.*;
import com.sun.source.util.*;
import java.io.*;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
import javax.lang.model.SourceVersion;
import javax.tools.*;
public class Solution {
public static void main(String[] args) throws Exception {
JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
System.out.println("No compiler: running on a runtime image without jdk.compiler");
return;
}
System.out.println("latest source version supported: "
+ (compiler.getSourceVersions().contains(SourceVersion.latest())));
Path dir = Files.createTempDirectory("compile");
try {
Path src = dir.resolve("src");
Path out = dir.resolve("out");
Files.createDirectories(out);
write(src, "demo/Greeter.java", """
package demo;
public class Greeter {
public static String greet(String name) {
return "Hello, " + name + "!";
}
}
""");
write(src, "demo/Main.java", """
package demo;
public class Main {
public static void main(String[] args) {
System.out.println(Greeter.greet(args.length > 0 ? args[0] : "world"));
}
}
""");
write(src, "bad/Broken.java", """
package bad;
import java.util.*;
public class Broken {
List raw = new ArrayList();
int count() {
String s = 42;
return s.length();
}
@Deprecated void old() {}
void caller() { undefined(); }
}
""");
System.out.println("\n== 1. run(): like the command line ==");
var outBuf = new ByteArrayOutputStream();
var errBuf = new ByteArrayOutputStream();
int rc = compiler.run(null, outBuf, errBuf,
"-d", out.toString(), "-sourcepath", src.toString(),
src.resolve("demo/Main.java").toString());
System.out.println("exit code " + rc + ", stderr bytes " + errBuf.size());
System.out.println("class files: " + listClasses(out));
System.out.println("\n== 2. Load and run the compiled code ==");
try (var loader = new URLClassLoader(new URL[] {out.toUri().toURL()})) {
Class<?> main = loader.loadClass("demo.Main");
Method m = main.getMethod("main", String[].class);
m.invoke(null, (Object) new String[] {"compiler API"});
}
System.out.println("\n== 3. getTask() with a DiagnosticCollector ==");
var collector = new DiagnosticCollector<JavaFileObject>();
try (StandardJavaFileManager fm = compiler.getStandardFileManager(
collector, Locale.US, StandardCharsets.UTF_8)) {
fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, List.of(out));
Iterable<? extends JavaFileObject> units =
fm.getJavaFileObjectsFromPaths(List.of(src.resolve("bad/Broken.java")));
JavaCompiler.CompilationTask task = compiler.getTask(
null, fm, collector, List.of("-Xlint:all", "-Xmaxerrs", "10"), null, units);
task.setLocale(Locale.US);
Boolean ok = task.call();
System.out.println("success: " + ok);
}
for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
String file = d.getSource() == null ? "-" : Path.of(d.getSource().toUri()).getFileName().toString();
System.out.printf("%-7s %s:%d:%d [%s] %s%n", d.getKind(), file, d.getLineNumber(),
d.getColumnNumber(), d.getCode(), d.getMessage(Locale.US).lines().findFirst().orElse(""));
}
Diagnostic<? extends JavaFileObject> first = collector.getDiagnostics().stream()
.filter(d -> d.getKind() == Diagnostic.Kind.ERROR).findFirst().orElseThrow();
String line = Files.readAllLines(src.resolve("bad/Broken.java")).get((int) first.getLineNumber() - 1);
System.out.println("first error line: " + line.strip());
System.out.println("position " + first.getStartPosition() + ".." + first.getEndPosition()
+ " -> \"" + Files.readString(src.resolve("bad/Broken.java"))
.substring((int) first.getStartPosition(), (int) first.getEndPosition()) + "\"");
System.out.println("\n== 4. Custom DiagnosticListener: count by kind ==");
Map<Diagnostic.Kind, Integer> counts = new EnumMap<>(Diagnostic.Kind.class);
DiagnosticListener<JavaFileObject> counter = d -> counts.merge(d.getKind(), 1, Integer::sum);
try (StandardJavaFileManager fm = compiler.getStandardFileManager(counter, Locale.US, StandardCharsets.UTF_8)) {
fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, List.of(out));
compiler.getTask(null, fm, counter, List.of("-Xlint:all"), null,
fm.getJavaFileObjectsFromPaths(List.of(src.resolve("bad/Broken.java")))).call();
}
System.out.println(counts);
System.out.println("\n== 5. Options: --release and -Werror ==");
write(src, "rel/UsesNew.java", """
package rel;
public class UsesNew {
void hello() { IO.println("Hello"); }
}
""");
for (String release : List.of("21", "25")) {
var c2 = new DiagnosticCollector<JavaFileObject>();
try (var fm = compiler.getStandardFileManager(c2, Locale.US, StandardCharsets.UTF_8)) {
fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, List.of(out));
boolean ok = compiler.getTask(null, fm, c2, List.of("--release", release), null,
fm.getJavaFileObjectsFromPaths(List.of(src.resolve("rel/UsesNew.java")))).call();
System.out.println("--release " + release + ": " + ok + (ok ? "" : " (" + c2.getDiagnostics().get(0).getCode() + ")"));
}
}
write(src, "warn/Raw.java", """
package warn;
public class Raw { java.util.List l = new java.util.ArrayList(); }
""");
int plain = compiler.run(null, null, OutputStream.nullOutputStream(), "-d", out.toString(),
"-Xlint:rawtypes", src.resolve("warn/Raw.java").toString());
int werror = compiler.run(null, null, OutputStream.nullOutputStream(), "-d", out.toString(),
"-Xlint:rawtypes", "-Werror", src.resolve("warn/Raw.java").toString());
System.out.println("warnings only: exit " + plain + ", with -Werror: exit " + werror);
System.out.println("\n== 6. JavacTask: parse and analyze without generating code ==");
try (var fm = compiler.getStandardFileManager(null, Locale.US, StandardCharsets.UTF_8)) {
JavacTask jt = (JavacTask) compiler.getTask(null, fm, null, List.of("-proc:none"), null,
fm.getJavaFileObjectsFromPaths(List.of(src.resolve("demo/Greeter.java"),
src.resolve("demo/Main.java"))));
List<String> events = new ArrayList<>();
jt.addTaskListener(new TaskListener() {
@Override public void finished(TaskEvent e) {
if (e.getKind() == TaskEvent.Kind.ANALYZE)
events.add("analyzed " + e.getTypeElement().getQualifiedName());
}
});
for (CompilationUnitTree cu : jt.parse()) {
new TreeScanner<Void, Void>() {
@Override public Void visitMethod(MethodTree m, Void p) {
System.out.println("method " + m.getName() + " returns " + m.getReturnType());
return super.visitMethod(m, p);
}
@Override public Void visitMethodInvocation(MethodInvocationTree mi, Void p) {
System.out.println(" calls " + mi.getMethodSelect());
return super.visitMethodInvocation(mi, p);
}
}.scan(cu, null);
}
jt.analyze();
events.sort(null);
events.forEach(System.out::println);
}
System.out.println("\n== 7. java.util.spi.ToolProvider: other JDK tools in-process ==");
for (String name : List.of("javac", "jar", "javap", "jlink")) {
System.out.println(name + " available: " + ToolProvider.findFirst(name).isPresent());
}
ToolProvider javap = ToolProvider.findFirst("javap").orElseThrow();
var sw = new StringWriter();
javap.run(new PrintWriter(sw), new PrintWriter(Writer.nullWriter()),
"-cp", out.toString(), "demo.Greeter");
sw.toString().lines().filter(l -> !l.startsWith("Compiled from")).forEach(System.out::println);
ToolProvider jar = ToolProvider.findFirst("jar").orElseThrow();
Path jarFile = dir.resolve("demo.jar");
int jrc = jar.run(System.out, System.err, "--create", "--file", jarFile.toString(),
"--main-class", "demo.Main", "-C", out.toString(), "demo");
System.out.println("jar exit " + jrc + ", jar exists: " + Files.exists(jarFile));
} finally {
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
}
static void write(Path root, String name, String content) throws IOException {
Path p = root.resolve(name);
Files.createDirectories(p.getParent());
Files.writeString(p, content);
}
static List<String> listClasses(Path out) throws IOException {
try (var s = Files.walk(out)) {
return s.filter(p -> p.toString().endsWith(".class"))
.map(p -> out.relativize(p).toString().replace(File.separatorChar, '/')).sorted().toList();
}
}
}
latest source version supported: true
== 1. run(): like the command line ==
exit code 0, stderr bytes 0
class files: [demo/Greeter.class, demo/Main.class]
== 2. Load and run the compiled code ==
Hello, compiler API!
== 3. getTask() with a DiagnosticCollector ==
success: false
WARNING Broken.java:6:5 [compiler.warn.raw.class.use] found raw type: java.util.List
WARNING Broken.java:6:20 [compiler.warn.raw.class.use] found raw type: java.util.ArrayList
ERROR Broken.java:8:20 [compiler.err.prob.found.req] incompatible types: int cannot be converted to java.lang.String
ERROR Broken.java:12:21 [compiler.err.cant.resolve.location.args] cannot find symbol
first error line: String s = 42;
position 126..128 -> "42"
== 4. Custom DiagnosticListener: count by kind ==
{ERROR=2, WARNING=2}
== 5. Options: --release and -Werror ==
--release 21: false (compiler.err.cant.resolve.location)
--release 25: true
warnings only: exit 0, with -Werror: exit 1
== 6. JavacTask: parse and analyze without generating code ==
method greet returns String
method main returns void
calls System.out.println
calls Greeter.greet
analyzed demo.Greeter
analyzed demo.Main
== 7. java.util.spi.ToolProvider: other JDK tools in-process ==
javac available: true
jar available: true
javap available: true
jlink available: true
public class demo.Greeter {
public demo.Greeter();
public static java.lang.String greet(java.lang.String);
}
jar exit 0, jar exists: true
Common questions
Why does ToolProvider.getSystemJavaCompiler() return null?
The program runs on a runtime without the jdk.compiler module: a jlink image or a JRE-style distribution. Run it on a full JDK, or add jdk.compiler to the image (jlink --add-modules jdk.compiler,...).
How do I compile against the libraries my application uses?
Pass -classpath with System.getProperty("java.class.path") (the default) or the specific JARs, or set StandardLocation.CLASS_PATH on the file manager. In a modular application, use --module-path and --add-modules.
Is the Compiler API faster than running javac as a process?
Yes, noticeably for repeated compilations: no JVM startup, and a reused file manager caches directory listings. The compiler itself still takes hundreds of milliseconds for the first compilation, while the JIT warms up.
Which JDK tools are available through java.util.spi.ToolProvider?
On JDK 25: javac, jar, javap, javadoc, jlink, jmod, jdeps, jpackage and jnativescan; ServiceLoader.load(ToolProvider.class) lists them at run time. jshell, keytool, jarsigner and jcmd are not, so use the JShell API (article 79) or run them as processes.
How do I get compiler messages in English regardless of the user's locale?
Pass Locale.ENGLISH (or Locale.ROOT) to getStandardFileManager and call task.setLocale(Locale.ENGLISH). Better still, react to getCode(), which doesn't depend on the language.
Can I compile code for an older Java version?
Yes, with --release 17 (or any supported version), which checks the code against that release's API as well as its language level. compiler.getSourceVersions() lists what the running compiler supports.
API reference
| Method | Purpose |
|---|---|
javax.tools.ToolProvider.getSystemJavaCompiler() | the platform compiler, or null |
JavaCompiler.run(in, out, err, String... args) | command-line style compilation |
getTask(Writer, JavaFileManager, DiagnosticListener, Iterable<String>, Iterable<String>, Iterable<? extends JavaFileObject>) | prepare a compilation |
CompilationTask.call(), setLocale, setProcessors, addModules | run and configure a task |
getStandardFileManager(listener, locale, charset) | file-based file manager |
StandardJavaFileManager.setLocationFromPaths, getJavaFileObjectsFromPaths, getJavaFileObjects | locations and compilation units |
DiagnosticCollector.getDiagnostics() | collected diagnostics |
Diagnostic.getKind/getSource/getLineNumber/getColumnNumber/getStartPosition/getEndPosition/getCode/getMessage | diagnostic details |
JavacTask.parse(), analyze(), generate(), addTaskListener | compilation phases |
TreeScanner, TreePathScanner, Trees.instance(task) | walking syntax trees |
java.util.spi.ToolProvider.findFirst(name), run(out, err, args...) | in-process JDK tools |
Summary
ToolProvider.getSystemJavaCompiler()gives access tojavac; it returnsnullin runtimes withoutjdk.compiler.runbehaves like the command line and returns an exit code;getTask(...).call()gives control over files, options and diagnostics.StandardJavaFileManagermaps locations such asCLASS_OUTPUTand turns paths into compilation units; close it after use.- Collect
Diagnosticobjects withDiagnosticCollectoror a custom listener; usegetCode()for programmatic decisions and positions for highlighting. - Use
--releaseto check API usage against an older Java version and-Werrorto fail on warnings. JavacTaskexposes parsing and analysis for tools that inspect source code.java.util.spi.ToolProviderrunsjar,javap,jlinkand other tools in-process.
Practice Questions
1. Your application calls ToolProvider.getSystemJavaCompiler() and gets null in production, though it works in the IDE. What is the likely cause?
Production runs on a runtime image that does not contain the jdk.compiler module, typically a jlink-built image or a minimal container base image. The IDE runs on a full JDK. Add jdk.compiler to the jlink --add-modules list (or requires jdk.compiler in a modular application), or use a full JDK base image.
2. Why is getTask with a DiagnosticCollector preferable to run with an error stream when you need to show errors in a web IDE?
run produces formatted text, whose layout and wording depend on the JDK version and locale, so you would have to parse it. Diagnostics are structured: kind, source file, line, column, start and end offsets and a stable code, which map directly to editor markers. You also choose the message locale with getMessage(locale).
3. A file contains both a missing semicolon and a type error, but the collector reports only the semicolon. Why?
javac stops after the parse phase when there are syntax errors, because later phases need a valid syntax tree. Type checking (attribution) only runs once the file parses, so the type error is reported in the next compilation after the semicolon is fixed.
4. A library must work on Java 21, but the build uses JDK 25. Why use --release 21 instead of -source 21 -target 21?
-source and -target control the language level and class file version, but the code is still compiled against the JDK 25 class library, so accidental uses of methods added after Java 21 compile and fail at run time with NoSuchMethodError. --release 21 compiles against a record of the Java 21 public API, so such uses are compile errors.
5. How would you list every method called in a set of source files without generating class files?
Create a task, cast it to JavacTask, call parse() and scan each CompilationUnitTree with a TreeScanner that overrides visitMethodInvocation. For resolved targets (which class the method belongs to), also call analyze() and use Trees.instance(task).getElement(path) from a TreePathScanner. Never call generate(), so no class files are written.
Previous: Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
Next: Compiling Java Code in Memory: Custom File Objects and Dynamic Code Generation
Related reading
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
- JShell Tutorial: Java's Interactive REPL for Quick Experiments

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.
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.
Discussion
Sign in to ask a question or share what you learned.