Java 9 updates for processing an API

Java 9 provides a refined Process API to control and manage the process with better performance in your operating system.

Process control could be made easier by accessing the process ID (PID), username, and resource utilization with the processing path information from the operating system. The multithreaded approach from previous versions is refined to easily deal with process trees and destruct or manage processes that have multiple subprocesses.

The following is an example of retrieving the PID of the current process with this API:

private static int getOwnProcessID(){
return ProcessHandle.current().getPid();
}

The following is a code snippet for getting a list of all the processes running on the operating system:

private static void listProcesses(){
ProcessHandle.allProcesses().forEach((h) -> printHandle(h));
}

private static void printHandle(ProcessHandle procHandle) {
// get info from handle
ProcessHandle.Info procInfo = procHandle.info();
System.out.println("PID: " + procHandle.getPid());
System.out.print("Start Parameters: ");
String[] empty = new String[]{"-"};
for (String arg : procInfo.arguments().orElse(empty)) {
System.out.print(arg + " ");
}
System.out.println();
System.out.println("Path: " + procInfo.command().orElse("-"));
System.out.println("Start: " + procInfo.startInstant().
orElse(Instant.now()).toString());
System.out.println("Runtime: " + procInfo.totalCpuDuration().
orElse(Duration.ofMillis(0)).toMillis() + "ms");
System.out.println("User: " + procInfo.user());
}


In the previous example, we exited the execution of operating-system-dependent applications and regex for the resulting output.

We can also get the handle of a process directly if we know the PID; we can do this by simply calling ProcessHandle.of(pid).

Obviously, this is a much cleaner way than checking the operating system and splitting the String with an appropriate regex. This is more of an operating-system-independent code that makes Java more flexible for distributed and parallel computing processes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset