English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java Topics

Java 9 Improved Process API

Java 9 New Features

In Java 9 Previously, the Process API lacked basic support for using local processes, such as obtaining the PID and owner of the process, the start time of the process, how much CPU time the process used, and how many local processes are running, etc.

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

An example of the ProcessHandle interface identifies a local process, which allows querying the process status and managing the process.

The ProcessHandle nested interface Info allows developers to escape the predicament of having to use local code frequently to obtain the PID of a local process.

We cannot provide method implementations in an interface. If we want to provide a combination of abstract methods and non-abstract methods (methods with implementations), then we must use an abstract class.

The onExit() method declared in the ProcessHandle interface can be used to trigger certain operations when a process terminates.

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: %n", p.pid());
      System.out.printf("Command name: %n", info.command().orElse(np));
      System.out.printf("Command line: %n", info.commandLine().orElse(np));
 
      System.out.printf("Start time: %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 following example execution output is as follows:

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 New Features