Open In App

Process API Updates in Java

By Process API, we can perform any operation related to a process.
Suppose if we want the process id of current running process, or we want to create a new process, or want to destroy already running process, or want to find the child and parent processes of current running process, or if we want to get any information regarding a process, then we can use Process API updates.
Java 9 Process API Updates: – 

ProcessHandle(I): – 



ProcessHandle ph = ProcessHandle.current();
ProcessHandle ph = p.toHandle(); //p is a process object
Optional obj = ProcessHandle.of(PID);
ProcessHandle ph = obj.get();




public class Demo {
 
    public static void main(String[] args)
    {
        ProcessHandle ph = ProcessHandle.current();
        long id = ph.pid();
        System.out.println("Id of the current process is : " + id);
    }
}

Id of the current process is : 5420

ProcessHandle.Info(I): – 
Info is an inner interface present inside ProcessHandle interface.
We can get complete information of the given or current running process.
To create ProcessHandle.Info object: – 
For this, first we need to create ProcessHandle object and then we will create ProcessHandle.Info object. 

ProcessHandle ph = ProcessHandle.current();
ProcessHandle.Indo pinfo = ph.info();

Methods in ProcessHandle.Info(I): – 



Optional o = info.user();
System.out.println("User is : "+o.get());
Optional o = info.command();
System.out.println("Command is : "+o.get());
Optional o = info.startInstant();
System.out.println("Time of process start is : "+o.get());
Optional o = info.totalCpuDuration();
System.out.println("Total CPU duration is : "+o.get());

Example: – 




public class Demo {
 
    public static void main(String[] args)
    {
        ProcessHandle ph = ProcessHandle.current();
        ProcessHandle.Info pinfo = ph.info();
        System.out.println("Complete process information is :" + pinfo);
        System.out.println("User of the process is : " + pinfo.user().get());
        System.out.println("Command used is : " + pinfo.command().get());
        System.out.println("Time of process starting is : " + pinfo.startInstant().get());
        System.out.println("Total CPU Duration is : " + pinfo.totalCpuDuration().get());
    }
}


Article Tags :