ProcessHandle Java 9 Process API with Examples
-
Last Updated:
-
By: Suraj S R
-
Series

Learn the processhandle java API from Java 9 with examples. Get the PID, read process info, list children, use onExit(), and destroy processes — step by step.
If you have ever tried to find out the process ID of your running Java program, you already know the old pain. Before Java 9, the language gave you almost nothing for this. The ProcessHandle java API changed that story completely. Now you can ask about any running process, read its details, watch for its exit, and even stop it, all in plain Java code.
In this guide, we will go through the Process API updates that arrived in Java 9. I will keep the language simple and the examples small. You will see real code that you can paste into your editor and run. Moreover, we will cover the common mistakes that trip up beginners, so you do not have to learn them the hard way.
This feature came in through JEP 102, which was titled “Process API Updates.” So everything here is standard Java. You do not need any external library. You only need a JDK on version 9 or higher, and honestly most teams today run on 17, 21, or 25, so you are more than covered.
Let us rewind a bit. Java always let you start a new program from your code. First there was Runtime.getRuntime().exec(), and later Java 5 gave us the cleaner ProcessBuilder. Both of these could launch a process and hand you back a Process object. That part worked fine.
The trouble started right after. Once a process was running, you could barely inspect it. You could not get its process ID easily. You could not see who owns it, when it started, or how much CPU it had used. Developers often fell back to ugly tricks. For example, some people parsed the output of operating system commands like ps or tasklist just to read a PID.
That approach was fragile and not portable. A command that works on Linux may fail on Windows. The code became messy, and it broke whenever the OS output changed slightly. Clearly, Java needed a proper, built-in way to handle this. That is exactly the gap Java 9 filled.
| 💡 INTERVIEW INSIGHT A classic interview question is: “Before Java 9, how did you get the PID of the current Java process?” The honest answer is that there was no clean, official API. People used workarounds like ManagementFactory.getRuntimeMXBean().getName(), which returned something like “12345@hostname”, and then split the string on the @ sign. Mentioning that you know this old hack, and that ProcessHandle.current().pid() replaced it, shows real depth. |
ProcessHandle is a new interface added to the java.lang package in Java 9. Think of it as a remote control for an operating system process. The process itself lives in the OS, and the handle is your Java-side reference to it. Through this handle, you can query the process and manage its life cycle.
So the whole idea of processhandle java is to give you one clean, official entry point for process work. Before this, the tools were scattered and OS-dependent. Now a single interface covers inspection, listing, and control in a portable way. That is a big quality-of-life upgrade for backend and tooling developers.
There is also a second piece called ProcessHandle.Info. This is a nested interface, and its job is to hold a snapshot of details about one process. It tells you things like the command that started the process and the user who runs it. We will look at Info closely in a later section.
Here is the key idea to hold on to. A ProcessHandle does not have to come from a process that your Java code started. It can point to processes already running on your machine, such as a browser or a database. That is a big jump from the old days, when you could only touch processes you launched yourself.

Let us start with the simplest and most useful example. Very often you just want to know about the Java program that is running right now. For that, you call the static method ProcessHandle.current(). It returns a handle to your own JVM process.
Once you have that handle, the pid() method gives you the native process ID as a long. No string parsing, no OS commands, nothing fragile. Here is the whole thing in a few lines.
public class CurrentProcessDemo {
public static void main(String[] args) {
// Handle to the currently running JVM process
ProcessHandle current = ProcessHandle.current();
long pid = current.pid();
System.out.println("My process ID is: " + pid);
System.out.println("Is it alive? " + current.isAlive());
}
}Run this, and you will see your real PID printed on the console. The isAlive() method returns true here, which makes sense, because the process asking the question is obviously still running. Short, clean, and portable across Windows, Linux, and macOS.
| 💡 GOOD TO KNOW ProcessHandle.current() gives you a handle, but it is a protected one. You are not allowed to destroy the current process through it. If you call destroy() on the current handle, Java will not let you shut yourself down this way. This is a safety guard, and it is worth remembering. |
Knowing the PID is nice, but usually you want more. You may want the command that launched a process, its start time, or its CPU usage. The info() method on a handle returns a ProcessHandle.Info object. This object carries that snapshot of details for you.
The Info interface gives you a small set of reader methods. Notice one important thing first. Almost every one of them returns an Optional. That design is deliberate, because not every operating system can supply every detail. An empty Optional simply means the OS did not share that value.
import java.time.Duration;
import java.time.Instant;
public class ProcessInfoDemo {
public static void main(String[] args) {
ProcessHandle.Info info = ProcessHandle.current().info();
info.command().ifPresent(cmd -> System.out.println("Command : " + cmd));
info.user().ifPresent(user -> System.out.println("User : " + user));
info.startInstant().ifPresent(t -> System.out.println("Started : " + t));
info.totalCpuDuration()
.ifPresent(d -> System.out.println("CPU used: " + d.toMillis() + " ms"));
}
}Here I used ifPresent on each Optional. Because the value may be missing, this style is clean and safe. It only prints a line when the data actually exists. As a result, you avoid null checks and avoid crashes on operating systems that hide some fields.
| 💡 INTERVIEW INSIGHT Interviewers love to ask why the Info methods return Optional instead of plain values. The reason is portability. The JDK runs on many operating systems, and each one exposes different process details. Returning Optional lets Java admit “this data may not exist here” without throwing exceptions or returning confusing nulls. It pushes you to write safe, defensive code. |
So far we looked at the current JVM. Now let us start a brand new process and watch it. You still use ProcessBuilder to launch it, just like before Java 9. The new part is the toHandle() method on the returned Process object. It converts the Process into a ProcessHandle.
Actually, you do not always need toHandle(). The Process class itself got the same helper methods in Java 9, such as pid(), info(), and onExit(). Still, toHandle() is handy when some method only accepts a ProcessHandle. Let us start a simple sleep command and inspect it.
public class SpawnDemo {
public static void main(String[] args) throws Exception {
// Start an external process (sleep for 5 seconds)
ProcessBuilder pb = new ProcessBuilder("sleep", "5");
Process process = pb.start();
System.out.println("Spawned PID : " + process.pid());
// Convert the Process to a ProcessHandle if you need one
ProcessHandle handle = process.toHandle();
handle.info().commandLine()
.ifPresent(line -> System.out.println("Command line: " + line));
}
}On Windows the sleep command may not exist, so swap it for something like notepad or ping. The point stays the same. You launch a real process, grab its PID instantly, and read its details through the handle. No parsing, no hacks.
One of the best additions in Java 9 is onExit(). In the past, if you wanted to wait for a process to finish, you called waitFor(), which blocked your thread. That meant your code just sat there and could do nothing else. The new onExit() method fixes this beautifully.
The onExit() method returns a CompletableFuture. This future completes the moment the process exits, whether it ended well or badly. Because it is a CompletableFuture, you can attach follow-up actions and keep your main thread free. Here is a non-blocking example.
import java.util.concurrent.CompletableFuture;
public class OnExitDemo {
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder("sleep", "3").start();
System.out.println("Started PID " + process.pid() + ", doing other work...");
// Register a callback that fires when the process exits
CompletableFuture<Process> future = process.onExit();
CompletableFuture<Void> done = future.thenAccept(p ->
System.out.println("Process " + p.pid()
+ " ended with exit code " + p.exitValue()));
// Keep the JVM alive until the callback has run
done.get();
System.out.println("Main thread is done.");
}
}Notice that Process.onExit() completes with a Process, while ProcessHandle.onExit() completes with a ProcessHandle. The difference is small but useful. A Process gives you exitValue(), whereas a bare ProcessHandle does not track the exit code. Pick whichever type fits your need.
| 💡 INTERVIEW INSIGHT A sharp question is the difference between waitFor() and onExit(). The method waitFor() is blocking, so your thread stops until the process ends. In contrast, onExit() is non-blocking and returns a CompletableFuture, so you can chain reactions and stay responsive. Mentioning that onExit() on the current process throws IllegalStateException is a nice bonus that shows you read the docs. |
Processes often start other processes. A build tool may launch a compiler, which may launch more helpers. Java 9 lets you walk this family tree. The children() method gives you the direct children of a process. The descendants() method goes deeper and returns children, their children, and so on.
Both methods return a Stream of ProcessHandle. So you can filter, map, and loop over them using the Stream API you already know. Keep in mind that the result is a snapshot. A process in the list might have already exited by the time you read it, so guard your code.
import java.util.stream.Stream;
public class ChildrenDemo {
public static void main(String[] args) {
ProcessHandle current = ProcessHandle.current();
Stream<ProcessHandle> children = current.children();
children.forEach(child ->
System.out.println("Direct child PID: " + child.pid()));
System.out.println("---- all descendants ----");
current.descendants().forEach(d ->
System.out.println("Descendant PID: " + d.pid()));
}
}If your Java program has not started any sub-processes, these streams may be empty. That is normal, not a bug. To actually see output, start a child process first, then call children(). This way the family tree has something real to show.
Sometimes you want a wider view. The static method ProcessHandle.allProcesses() returns a Stream of every process that your Java program is allowed to see. It is a snapshot of the whole machine at that moment, not a live feed.
This method is powerful, so use it with care. On a busy server there could be hundreds of processes. Therefore, it is smart to filter the stream and limit the output. Below I print only the first ten processes along with their commands.
public class AllProcessesDemo {
public static void main(String[] args) {
ProcessHandle.allProcesses()
.limit(10)
.forEach(ph -> {
String cmd = ph.info().command().orElse("unknown");
System.out.println(ph.pid() + " -> " + cmd);
});
}
}Here I used orElse(“unknown”) on the Optional returned by command(). That gives a clean fallback when the OS hides the command name. The limit(10) call keeps the console readable. Try removing it only if you really want the full list.
The API also lets you end a process. There are two methods for this. The destroy() method asks the process to shut down in a normal, polite way. The destroyForcibly() method is the hard kill, and it tries to stop the process immediately.
Both methods return a boolean. The value tells you whether the request to terminate was actually sent, not whether the process is already gone. There is also supportsNormalTermination(), which tells you if a normal shutdown is even possible on your platform.
public class DestroyDemo {
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder("sleep", "30").start();
ProcessHandle handle = process.toHandle();
System.out.println("Can terminate normally? "
+ handle.supportsNormalTermination());
// Ask the process to stop
boolean requested = handle.destroy();
System.out.println("Destroy requested: " + requested);
// Wait and confirm it is gone
handle.onExit().get();
System.out.println("Still alive? " + handle.isAlive());
}
}After calling destroy(), I wait on onExit() so the program pauses until the process really ends. Then isAlive() returns false, which confirms the kill worked. Prefer destroy() first, and keep destroyForcibly() as a last resort when a process refuses to stop.
| 💡 INTERVIEW INSIGHT Expect a question on destroy() versus destroyForcibly(). The first one requests a graceful shutdown, which lets the process clean up. A forced kill is what destroyForcibly() does, with no cleanup chance. Also note that the return boolean means “request sent,” not “process stopped.” And remember, you cannot destroy the current process through ProcessHandle.current(), which is a built-in safety rule. |
What if you already know a process ID and want a handle to it? The static method ProcessHandle.of(long pid) is made for exactly this. It takes a PID and returns an Optional of ProcessHandle. The Optional is empty when no process with that ID exists.
This design is honest and safe. A process may have exited between the time you learned its PID and the time you looked it up. By returning an Optional, Java forces you to handle that “not found” case properly. Here is a short example.
import java.util.Optional;
public class FindByPidDemo {
public static void main(String[] args) {
long somePid = 1234; // replace with a real PID on your machine
Optional<ProcessHandle> maybe = ProcessHandle.of(somePid);
maybe.ifPresentOrElse(
ph -> System.out.println("Found process, alive? " + ph.isAlive()),
() -> System.out.println("No process with PID " + somePid)
);
}
}I used ifPresentOrElse here, which is a clean way to handle both outcomes. When the process exists, the first branch runs. When it does not, the second branch runs. This keeps the code readable and avoids a messy if-else block.
Java 9 did not stop at the new interfaces. It also upgraded the old java.lang.Process class. So the Process object you get from ProcessBuilder.start() now carries several fresh helper methods. This means you often do not even need to call toHandle() first.
Because of these additions, your code stays short and natural. You start a process, then call process.pid() or process.info() straight away. The old and new APIs blend together smoothly, which made migration painless for most teams.
Let us put a few pieces together in one tiny program. Imagine you launch a helper process and want to log its details. You also want a message when it finishes, without blocking your main thread. This mixes info(), onExit(), and pid() in a natural flow.
import java.util.concurrent.CompletableFuture;
public class RealWorldDemo {
public static void main(String[] args) throws Exception {
Process worker = new ProcessBuilder("sleep", "2").start();
long pid = worker.pid();
worker.info().user()
.ifPresent(u -> System.out.println("Owner of " + pid + " is " + u));
// Non-blocking: log when the worker is done
CompletableFuture<Void> done = worker.onExit().thenAccept(p ->
System.out.println("Worker " + p.pid() + " finished."));
System.out.println("Main thread keeps running meanwhile...");
done.get(); // wait for the callback before exiting the demo
}
}This short snippet shows how friendly the API feels in practice. You read the owner, you set up a callback, and you keep your main thread free. In a real service you would replace the print lines with proper logging. Still, the shape of the code stays this simple.
One more tip for daily work. The handle returned by these methods is immutable and thread-safe. So you can pass it between threads without extra locking. That makes it a good fit for modern, concurrent Java programs where many tasks run at once.
The Process API is friendly, but a few traps catch new users. Let us list them so you can skip the frustration. These issues come up often on forums and during code reviews.
Many Info methods return Optional, and some developers call get() on them blindly. If the OS did not supply that value, get() throws a NoSuchElementException. Always use ifPresent, orElse, or map instead. That keeps your program safe on every platform.
Process details depend heavily on the operating system. A field like totalCpuDuration() may be present on Linux yet missing on another setup. So do not hard-code assumptions. Test your code on the platforms you actually target, and handle empty values gracefully.
Methods like allProcesses(), children(), and descendants() return a snapshot. A process in that list can die a millisecond later. Therefore, wrap your actions in checks, and expect that a handle may point to something already gone. Robust code assumes change.
Calling destroy() on ProcessHandle.current() will not shut down your JVM. This guard exists on purpose. If you truly need to end your own program, use System.exit() with a status code instead.
You will not reach for this API every day, and that is fine. It shines in specific situations. Knowing when to use it helps you write cleaner tools and services. The list below shows the spots where it truly earns its place in real projects.
In short, whenever your Java program needs to be aware of operating system processes, this API is the right tool. It is standard, portable, and modern. Moreover, the same concepts carry forward unchanged into Java 17, 21, and 25, so learning it now pays off for years.
A: ProcessHandle is an interface added to java.lang in Java 9. It acts like a handle to an operating system process, letting you read its PID, inspect details, list related processes, and control its life cycle — all in pure Java with no OS commands.
A: Call ProcessHandle.current().pid(). It returns the native process ID as a long. Before Java 9 there was no clean API, so developers parsed ManagementFactory.getRuntimeMXBean().getName() and split on the @ sign.
A: Because process details differ by operating system. Each OS exposes different fields, so returning Optional lets Java admit a value may be missing instead of returning null or throwing an exception. Use ifPresent or orElse to stay safe.
A: destroy() requests a graceful shutdown so the process can clean up. destroyForcibly() is a hard kill with no cleanup. Both return a boolean that means the request was sent, not that the process has stopped.
A: waitFor() blocks the current thread until the process ends. onExit() is non-blocking and returns a CompletableFuture that completes when the process exits, so you can chain follow-up actions and keep your thread free.
A: Yes. ProcessHandle.of(long pid) returns an Optional<ProcessHandle>. The Optional is empty if no process with that ID exists, which handles the case where the process already exited.
The Java 9 Process API gave developers something they had wanted for a long time. With ProcessHandle, you can finally read a process ID, inspect details, list related processes, and react to exits, all in pure Java. No OS commands, no string hacks, no external libraries.
We covered the core pieces step by step. You saw current() for the running JVM, of() to look up a PID, and allProcesses() for a full view. You also met info() for details, onExit() for non-blocking callbacks, and destroy() for termination. Along the way we flagged the Optional pattern and the snapshot behavior that beginners often miss.
Try these small programs on your own machine. Change the commands, print more fields, and watch the output. Hands-on practice makes this API stick far better than reading alone. Once it clicks, you will wonder how you ever managed without it.
One last thought before you go. Even though Java 9 itself is old now, this API is not. It ships unchanged in every modern release, and tools you build on it keep working. So treat this as a foundation skill, not a historical one. The time you spend here will serve you across Java 17, 21, and beyond.