• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Java 9 : Use Process API to Get Process Information

August 8, 2015 //  by Mohamed Sanaulla//  Leave a Comment

With every one focused on Java 8, let me take you through some of the features in Java 9. As Java 9 is being continuously under development features discussed here might change before the final release of JDK 9.

Few links to start with:

  1. In this post I am using Java 9 Build b75 downloaded from here.
  2. The Javadocs for Java 9 can be found here.

Process API

The details of the Process API updates can be found here in the official project page. In this post I am going to show you how to:

Process API in Java 9

  1. Print details of the current process i.e the JVM process
  2. Print the details of all the processes running in the system
  3. Print the details of the newly created process

A new Java class by name ProcessHandle has been introduced which is described as:

ProcessHandle identifies and provides control of native processes. Each individual process can be monitored for liveness, list its children, get information about the process or destroy it.

The Process class has been enhanced with the Process APIs to get ProcessHandle for that process, to get the process info, to get process id.

In the subsequent post I will use the below utility method to print the process information. ProcessHandle class provides info() method which returns an instance of ProcessHandle.Info, this instance can be used to get the following details:

  • Executable pathname for the process.
  • Arguments if any of the process.
  • Start time of the process.
  • Total CPU time of the process.
  • User of the process.
//The code for utility class
import java.time.Instant;
import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class ProcessAPIDemoUtil{
  public static void printProcessDetails(ProcessHandle currentProcess){
    //Get the instance of process info
    ProcessHandle.Info currentProcessInfo = currentProcess.info();
    if ( currentProcessInfo.command().orElse("").equals("")){
      return;
    }
    //Get the process id
    System.out.println("Process id: " + currentProcess.getPid());
    //Get the command pathname of the process
    System.out.println("Command: " + currentProcessInfo.command().orElse(""));
    //Get the arguments of the process
    String[] arguments = currentProcessInfo.arguments().orElse(new String[]{});
    if ( arguments.length != 0){
      System.out.print("Arguments: ");
      for(String arg : arguments){
        System.out.print(arg + " ");
      }
      System.out.println();
    }
    //Get the start time of the process
    System.out.println("Started at: " + currentProcessInfo.startInstant().orElse(Instant.now()).toString());
    //Get the time the process ran for
    System.out.println("Ran for: " + currentProcessInfo.totalCpuDuration().orElse(Duration.ofMillis(0)).toMillis() + "ms");
    //Get the owner of the process
    System.out.println("Owner: " + currentProcessInfo.user().orElse(""));
  }
}

Print details of the current process i.e the JVM process

The ProcessHandle class provides a API current() to get the current process handle. This current process is nothing but the JVM process which is executing the java code. The below code retrieves the current process and prints its details using the above utility method:

public class CurrentProcessDemo{
  public static void main(String[] args){
    //Get the handle for current process i.e the JVM process
    ProcessHandle currentProcess = ProcessHandle.current();
    System.out.println("**** Current process info ****");
    ProcessAPIDemoUtil.printProcessDetails(currentProcess);
  }
}

The output of the above code is:

G:\java9>javac CurrentProcessDemo.java

G:\java9>java CurrentProcessDemo
**** Current process info ****
Process id: 8896
Command: C:\Program Files\Java\jdk1.9.0\bin\java.exe
Started at: 2015-08-08T14:08:06.756Z
Ran for: 187ms
Owner: SANA-LAPTOP\Mohamed

Print the details of all the processes running in the system

The ProcessHandle class provides an API allProcesses() to get all active processes running in the system. As there are many processes returned, I am going to filter out those not having any command associated with and limit the results to 3. Below is the code for retrieving the processes:

public class GetAllProcessesDemo{
  public static void main(String[] args){
    //list atmost 5 processes running in the system which have some command
    ProcessHandle.allProcesses()
      .filter(processHandle -> processHandle.info().command().isPresent())
      .limit(3)
      .forEach((process) ->{
        ProcessAPIDemoUtil.printProcessDetails(process);
      });
  }
}

The output for above code:

G:\java9>javac GetAllProcessesDemo.java

G:\java9>java GetAllProcessesDemo
Process id: 4524
Command: C:\Windows\System32\taskhostw.exe
Started at: 2015-08-04T12:19:49.342Z
Ran for: 10609ms
Owner: SANA-LAPTOP\Mohamed
Process id: 4540
Command: C:\Windows\System32\sihost.exe
Started at: 2015-08-04T12:19:49.364Z
Ran for: 67125ms
Owner: SANA-LAPTOP\Mohamed
Process id: 4560
Command: C:\Program Files\Synaptics\SynTP\SynTPEnh.exe
Started at: 2015-08-04T12:19:49.449Z
Ran for: 852609ms
Owner: SANA-LAPTOP\Mohamed

G:\java9>

Print the details of the newly created process

The Process class has been enhanced with APIs to get process info, process id and the ProcessHandle for that process. Below is the code to get the details of the newly created process:

import java.io.IOException;
import java.io.*;
import java.util.*;

public class NewProcessDetailDemo{
  public static void main(String[] args) throws IOException{
    //Create a new process
    Process process = Runtime.getRuntime().exec("cmd /k dir");
    System.out.println("**** Process details for created process ****");
    //now print this process details
    ProcessAPIDemoUtil.printProcessDetails(process.toHandle());
    Scanner reader = new Scanner(process.getInputStream());
    while(reader.hasNext()){
      System.out.println(reader.nextLine());
    }

    reader.close();
  }
}

The output of the above code is:


G:\java9>javac NewProcessDetailDemo.java

G:\java9>java NewProcessDetailDemo
**** Process details for created process ****
Process id: 7532
Command: C:\Windows\System32\cmd.exe
Started at: 2015-08-08T14:39:06.148Z
Ran for: 0ms
Owner: SANA-LAPTOP\Mohamed
 Volume in drive G is Development Base
 Volume Serial Number is 9E68-AF66

 Directory of G:\java9

08/07/2015  08:13 PM    <DIR>          .
08/07/2015  08:13 PM    <DIR>          ..
08/08/2015  07:38 PM               642 CurrentProcessDemo.class
08/07/2015  07:33 PM               321 CurrentProcessDemo.java
08/08/2015  07:42 PM             1,717 GetAllProcessesDemo.class
08/08/2015  07:42 PM               378 GetAllProcessesDemo.java
08/07/2015  02:33 PM               427 HelloWorld.class
08/07/2015  02:33 PM               114 HelloWorld.java
08/08/2015  08:09 PM             1,144 NewProcessDetailDemo.class
08/08/2015  08:09 PM               595 NewProcessDetailDemo.java
08/07/2015  06:47 PM             3,191 ProcessAPIDemo.class
08/07/2015  08:12 PM             1,099 ProcessAPIDemo.java
08/08/2015  07:38 PM             1,845 ProcessAPIDemoUtil.class
08/08/2015  07:32 PM             1,333 ProcessAPIDemoUtil.java
              12 File(s)         12,806 bytes
               2 Dir(s)  110,687,162,368 bytes free

With this I have shown you how we can get process information using the new APIs in Java 9. In the coming posts I will explore more of the features of Java 9, so stay tuned. If you have any feedback, please write it in the comments section.

Category: JavaTag: Java 9 Features

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: «New Features in Spring Boot 1.4 Spring : @EventListener in Spring 4.2
Next Post: Spring Boot : External Configurations for Spring Boot Spring Boot Configurations»

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact