What is the importance of the ProcessHandle interface in Java 9?


ProcessHandle interface introduced in Java 9. It allows us to perform actions and check the state of a process that relates. This interface provides the process’s native process ID (pid), start time, accumulated CPU time, arguments, command, user, parent process, and descendants.

ProcessHandle interface allows us to perform the following actions.

  • It returns a ProcessHandle.Info containing further information about a process
  • The Pid of a process
  • If it is alive
  • Retrieve a snapshot of the direct children of a process
  • Retrieve a snapshot of all descents of a process
  • Retrieve a snapshot of all currently running processes
  • Allow the process to be destroyed
  • It returns a CompletableFuture with a ProcessHandle for when the Progress is terminated


ProcessHandle.Info holds information from a snapshot of the process includes:

  • Command of the Process
  • Arguments of the Process
  • Command-line of the Process
  • The start time of the Process
  • CPU time used by the Process
  • The user of the Process

In the below example, we can print the pid of the current Process Handle by using the pid() method, and also checking the process is currently running by using the isAlive() method.

Example

import java.util.Optional;

public class ProcessHandleTest {
   public static void main(String args[]) {
      long pid = ProcessHandle.current().pid();

      ProcessHandle currentProcess = ProcessHandle.current();
      System.out.println("PID: " + currentProcess.pid());

      Optional<ProcessHandle> processHandle = ProcessHandle.of(pid);
      boolean isAlive = processHandle.isPresent() && processHandle.get().isAlive();
      System.out.println(isAlive);
   }
}

Output

PID: 6484
true

Updated on: 13-Mar-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements