Start United States USA — IT Java 9's other new enhancements, Part 3

Java 9's other new enhancements, Part 3

360
0
TEILEN

JEP 102 updates the Process API with an enhanced Process class and a new ProcessHandle interface for obtaining a process ID, obtaining additional information about a process, and executing actions on process termination.
JEP 102: Process API Updates enhances the java.lang. Process class and introduces the java.lang. ProcessHandle interface with its nested Info interface to overcome limitations that often force developers to resort to native code; for example, to obtain the native process ID (PID). This post introduces you to these upgrades.
Java 9 adds several new methods to the abstract Process class that let you identify direct child or descendent processes, obtain this Process ’s PID, return a snapshot of information about this Process , obtain a completable future to receive asynchronous notification when this Process exits, and more:
More than half of these methods work with the new ProcessHandle interface, which identifies and provides control of native processes. For example, toHandle() returns an object whose class implements ProcessHandle , and which is associated with this Process. ProcessHandle ’s methods are listed below:
Various Process methods delegate to their ProcessHandle counterparts by invoking toHandle() followed by the method name. For example, getPid() invokes toHandle().getPid() and info() invokes toHandle().info() , which returns a ProcessHandle. Info object. The nested Info interface provides the following methods:
Each method returns a java.util. Optional instance that may contain a non-null object reference or null, and is useful for avoiding java.lang. NullPointerException. You’ll learn how to work with these methods along with various ProcessHandle and new Process methods in subsequent sections.
Process ’s long getPid() method returns the PID of the invoking process. The method’s return type is long instead of int because PIDs are unsigned integers, the largest positive int value is around 2 million, and Linux can accommodate PIDs up to around 4 million. Listing 1 demonstrates getPid().
The java.lang. ProcessBuilder class (introduced in Java 5) constructs a process builder for the Windows notepad.exe program. The start() method is invoked to start notepad.exe , returning a Process object to interact with the new process. Process ’s getPid() method is subsequently invoked on the Process object and its value is output.
Before Java 5, the only way to spawn a new process was to use Runtime.

Continue reading...