Java 9 Improved Process API

Java 9 新特性Java 9 New Features

Before Java 9, the Process API still lacked basic support for using native processes, such as obtaining the PID and owner of a process, the start time of the process, how much CPU time the process has used, how many native processes are running, etc.

Java 9 added an interface named ProcessHandle to the Process API to enhance the java.lang.Process class.

An instance of the ProcessHandle interface identifies a native process, allowing querying of process status and managing the process.

ProcessHandle's nested interface Info helps developers escape the dilemma of having to use native code to obtain the PID of a local process.

We cannot provide method implementations in interfaces. If we want to provide a combination of abstract and non-abstract methods (methods with implementations), then we have to use abstract classes.

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 output of the above example 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

Java 9 新特性Java 9 New Features

Other Extensions