Learnitweb

Java 9 process API updates

1. Introduction

Until Java 8, Java SE provided limited support for native operative-system processes. This forced developers to resort to native code. Also, programmers have to write code based on operating system. To solve this issue, serval process API enhancements were introduced in Java 9.

The java.lang.Process class is enhanced to operating specific id of the process, information about the process including the arguments, the start time of the process, user name of the process, the accumulated cpu time of the process.

The java.lang.ProcessHandle class returns information about each process as provided by the operating system including process id, arguments, command, start time, etc. A ProcessHandle can return the parent of the process, the spawned child processes, and to all descendants via a stream of ProcessHandle.

ProcessHandle can be used to destroy monitor process liveness and destroy processes.

Note that the control of processes is limited by normal operating system access controls.

2. What is new in Java 9 Process API

  • Several new methods were added to the Process class like pid(), info().
  • New methods were added to the ProcessBuilder class such as startPipeline().
  • Introduced a new interface ProcessHandle. ProcessHandle identifies and provides control of native processes. Using this interface, we can access current running process, parent and child of a particular process.
  • Introduced new interface ProcessHandle.Info. This interface provides information snapshot about the process.

3. java.lang.ProcessHandle interface

ProcessHandle identifies and provides control of native processes. ProcessHandle can be used to get information about the process, destroy it, monitor liveness, list its children. This is in contrast to Process instance which is started by the current process and additionally provide access to the process input, output and error streams.

The process ID is assigned to the process by the operating system. Factory methods such as current(), of(long), children(), descendants(), parent() and allProcesses() are used to get ProcessHandles.

The ProcessHandle static factory methods return instances that are value-based, immutable and thread-safe.

4. How to get ProcessHandle object

ProcessHandle identifies and provides control of native processes. ProcessHandle can be used to monitor individual process for liveness, list its children, get other information about the process and even destroy it.

Let us see few ways to get ProcessHandle object.

ProcessHandle handle=ProcessHandle.current();Returns a ProcessHandle for the current process.
ProcessHandle handle=p.toHandle();Returns the ProcessHandle of specified Process object (in this case p).
Optional handle=ProcessHandle.of(PID);Returns the ProcessHandle of proccess with the specified pid.

5. Example of getting process ID of running process

public class ProcessHandleExample {
    public static void main(String[] args) throws Exception {
        ProcessHandle p = ProcessHandle.current();
        long pid = p.pid();
        System.out.println("The PID of current running JVM instance :" + pid);
        Thread.sleep(100000);
    }
}

You can check the process id is the same shown in the Task Manager.

6. Using ProcessHandle.Info to get process information

ProcessHandle.Info interface provides information snapshot about the process. The attributes of a process vary by operating system and are not available in all implementations.

Following are the methods of ProcessHandle.Info interface:

Optional arguments​()Returns an array of Strings of the arguments of the process.
Optional command​()Returns the executable pathname of the process.
Optional commandLine​()Returns the command line of the process.
Optional startInstant​()Returns the start time of the process.
Optional totalCpuDuration​()Returns the total cputime accumulated of the process.
Optional user​()Return the user of the process.

Following is an example of ProcessHandle:

public class ProcessHandleExample {
    public static void main(String[] args) throws Exception {
        ProcessHandle p=ProcessHandle.current();
        ProcessHandle.Info info=p.info();
        System.out.println("User of the process: "+info.user().get());
        System.out.println("Command line of the process: "+info.command().get());
        System.out.println("Start time of the process: "+info.startInstant().get());
        System.out.println("Total cputime accumulated of the process: "+info.totalCpuDuration().get());
    }
}

7. ProcessBuilder

ProcessBuilder class is used to create operating system processes. Note that this class is not synchronized. Each process builder manages these process attributes:

  • a command, a list of strings which signifies the external program file to be invoked and its arguments, if any.
  • an environment, which is a system-dependent mapping from variables to values.
  • a working directory. The default value is the current working directory of the current process
  • a source of standard input.
  • a destination for standard output and standard error.
  • a redirectErrorStream property.

7.1 Example to open Notepad using ProcessBuilder

public class ProcessBuilderExample {
    public static void main(String[] args) throws Exception {
              ProcessBuilder pb=new ProcessBuilder("notepad.exe");
        Process p=pb.start();
        System.out.println("Process Started with id:"+p.pid());
    }
}

8. Conclusion

In conclusion, the Java 9 process API updates bring significant improvements and new features to the Java platform, enhancing its capabilities for managing operating system processes. The introduction of the ProcessHandle class provides a more robust and flexible way to interact with processes, allowing developers to access vital information about running processes and exert greater control over them. Additionally, the ability to monitor process lifecycle events simplifies the task of managing and coordinating concurrent processes within Java applications. These updates not only streamline process management but also enhance the security and reliability of Java applications. Overall, the Java 9 process API updates represent a notable advancement in the Java ecosystem, empowering developers to build more efficient and resilient software solutions.