Java 9 Process API Improvements


Java 9 adds improvements to the Process API that deal with ongoing shortcommings like:

  • getting the PID of the running process
  • getting the children and/or the descendants of a process

Along with these a new class is added that helps:

  • listing all running processes
  • getting info for an arbitrary process
  • traversing process tree

Note: The information returned by these methods is just a snapshot of the processes running on the OS. Some of them may be missing, stopped etc. during the traversal so handle with care.


Showing Process Information

Sample showing obtaining information for running processes’ id and command

Getting information for a process returns Optional and based on that further filtering can be done. For example listing only processes that have available command property:

You can see there is no ‘N/A’ value for ‘Command’ in the output

Sample showing obtaining information for an arbitrary process

In this case the ‘pid’ is of the IDE used for writing the sample.

Getting the ID of the Running Process

Sample showing obtaining information for a process that was killed after taking a snapshot from the OS

The output of this snippet is:

In this case the PID is of a text editor. To repro start the sample code in debug and once the processHandler is obtained stop the text editor.

Traversing process tree

The output of this program is:

In this sample ‘pid’ is the running IDE. The output shows the difference between children() and descendants(). At the begging of the programm a new process is started however it is not listed when children() is called and it is shown when descendants() is called.

Sample Application

Sample application that shows:

  • all process when invoked with argument ‘ps’
  • process’ children when invoked with arguments ‘children <pid>’
  • process’ descendants when invoked with arguments ‘descendants <pid>’