Java 9 Improved Process API
Before Java 9, the Process API lacked basic support for using native processes, such as obtaining the process's PID and owner, the start time of the process, how much CPU time the process has used, and how many native processes are running.
Java 9 added an interface called ProcessHandle to enhance the java.lang.Process class.
An instance of the ProcessHandle interface identifies a native process and allows querying the process status and managing the process.
The ProcessHandle nested interface Info helps developers avoid the predicament of having to use native code to obtain a native process's PID.
We cannot provide method implementations in an interface. If we want to provide a combination of abstract and non-abstract methods (methods with implementations), we need to use an abstract class.
The onExit() method declared in the ProcessHandle interface can be used to trigger certain actions when a process terminates.
Example
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
String np = "Not Present";
Process p = pb.start();
ProcessHandle.Info info = p.info();
System.out.printf("Process ID : %s%n", p.pid());
System.out.printf("Command name : %s%n", info.command().orElse(np));
System.out.printf("Command line : %s%n", info.commandLine().orElse(np));
System.out.printf("Start time: %s%n",
info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
.toLocalDateTime().toString()).orElse(np));
System.out.printf("Arguments : %s%n",
info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
System.out.printf("User : %s%n", info.user().orElse(np));
}
}
The above example execution output is:
Process ID : 5800
Command name : C:\Windows\System32\notepad.exe
Command line : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator