Java 9 Improved Process API
Before Java 9, the Process API still lacked basic support for working with native processes, such as getting a process's PID and owner, the process start time, how much CPU time the process used, how many native processes are running, and so on.
Java 9 adds an interface named ProcessHandle to the Process API to enhance the java.lang.Process class.
An instance of the ProcessHandle interface identifies a native process; it allows querying the process state and managing the process.
ProcessHandle's nested interface Info frees developers from the awkward situation of often having to use native code just to get the PID of a local process.
We could not provide method implementations in interfaces. If we wanted to provide a combination of abstract and non-abstract methods (methods with implementations), we had to use abstract classes.
The onExit() method declared in the ProcessHandle interface can be used to trigger certain operations when a process terminates.
Example
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 : %s%n
"
,
p
.
pid
(
)
)
;
System
.
out
.
printf
(
"
Command name : %s%n
"
,
info
.
command
(
)
.
orElse
(
np
)
)
;
System
.
out
.
printf
(
"
Command line : %s%n
"
,
info
.
commandLine
(
)
.
orElse
(
np
)
)
;
System
.
out
.
printf
(
"
Start time: %s%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 output of the above example is:
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