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].



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 16516@Krakatau. 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.parseLong(jvmName.split("@")[0]);
        System.out.println("PID  = " + pid);

Here is the result of the code above:

Name = 16516@Krakatau
PID  = 16516


  1. I just found that the process with PID=8564 uses 25% of CPU while there was a blank screen saver on the desktop PC (win7, i5-3570K) while idle. Is the process PID generally unique, and what does that process 8564 (svchost.exe) do while PC is idle and blank screen saver is on?


Leave a Reply

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