In a previous blog post I wrote about one of my favourite features of Java 9, the JShell. At this post, I will write about another feature I am excited about. The new Java 9 Process API. I will also present some code showing how powerful and intuitive it is.
The new API adds greater flexibility to spawning, identifying and managing processes. As an example, before Java 9 someone would need to do the following in order to retrieve the PID of a running process:
The above is not intuitive and seems like a hack. It feels to someone that the Java process should at least easily expose its own PID.
Moreover, I quite a few times needed to spawn new child processes from inside a Java process and manage them. The process of doing so is very cumbersome. A reference to the child process has to be kept throughout the program’s execution if the developer wishes to destroy that process later. Not to mention that getting the PIDs of the children processes is also a pain.
Fortunately, Java 9 comes to fix those issues and provide a clean API for interaction with processes. More specifically two new interfaces has been added to the JDK:
The two new interfaces add quite a few methods. The first one methods for retrieving a PID, all the processes running in the system and also methods for relationships between processes. The second one mainly provides meta information about the process.
As someone would expect most of the methods have native, platform specific implementations. The OpenJDK’s implementation of ProcessHandle can be found here. Also the Unix specific implementation can be seen here.
I have created a very simple program which makes use of most of the features of this new Process API. The program does the below:
- Can retrieve the running process’ PID
- Can start a long running process
- Can start a short running process, which terminates about ~5seconds after starting
- Can list all child processes that were spawned by the parent one
- Can kill all child processes that were spawned by the parent one
- Attaches a callback when a child process exits. This is done using the onExit() method of the ProcessHandle
The sample class is provided below. For the entire example please see here: