Java 9 : How to get Current Process Information

Points to Remember

  1. Java 9 introduced the new Process Api in java.lang package.
  2. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes.

Read More

Get the Current Process Information.

In this example we will try to get information about the current process. For this we will use the method ProcessHandle.current() method, this will return the object ProcessHandle which can be used to get the information of the process.

import java.io.IOException;
import java.lang.ProcessHandle;

/**
 * @author ekiras
 */
public class CurrentProcess {

    public static void main(String[] args) throws IOException {
        currentProcessInfo();
    }

    public static void currentProcessInfo(){
        System.out.println("Current Process : ");
        ProcessHandle process = ProcessHandle.current();
        printProcessInfo(process);
    }


    public static void printProcessInfo(ProcessHandle processHandle){
        System.out.println("---------------------------------------------------------");
        System.out.println(" Process Id :: " + processHandle.getPid());
        System.out.println(" Process isAlive() :: " + processHandle.isAlive());
        System.out.println(" Process children :: " + processHandle.children().count());
        System.out.println(" Process supportsNormalTermination() :: " + processHandle.supportsNormalTermination());
        System.out.println(" Process Info :: " + processHandle.info().toString());

    }

}

The above code will produce the following output on console.

Current Process : 
---------------------------------------------------------
 Process Id :: 551
 Process isAlive() :: true
 Process children :: 0
 Process supportsNormalTermination() :: true
 Process Info :: [user: Optional[root], cmd: /opt/jdk-9/bin/java, args: [CurrentProcess], startTime: Optional[2016-11-14T07:45:33.440Z], totalTime: Optional[PT0.24S]]

No comments:

Powered by Blogger.