How do I get process id of a Java application?

The code below show you how to get the process id of a Java application. We can use the ManagementFactory.getRuntimeMXBean().getName() to get the process id. In Windows the method return a string in the form of [PID]@[MACHINE_NAME].

package org.kodejava.example.lang.management;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class GetProcessID {
    public static void main(String[] args) {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

        //
        // Get name representing the running Java virtual machine.
        // It returns something like [email protected] Where the value
        // before the @ symbol is the PID.
        //
        String jvmName = bean.getName();
        System.out.println("Name = " + jvmName);

        //
        // Extract the PID by splitting the string returned by the
        // bean.getName() method.
        //
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("PID  = " + pid);
    }
}

Here is the result of the code above:

Name = [email protected]
PID  = 8564
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply