How do I get the uptime of a JVM?

The following code snippet demonstrates how to get the time for how long has the JVM been running.

package org.kodejava.lang.management;

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

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

        // Returns the uptime of the Java virtual machine in
        // milliseconds.
        long uptime = bean.getUptime();
        System.out.printf("Uptime = %d (ms).", uptime);
    }
}

The output of the code snippet above:

Uptime = 125 (ms).

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

Since JDK 10, we can use ManagementFactory.getRuntimeMXBean().getPid() method to get the process ID. This method returns the process ID representing the running Java virtual machine.

package org.kodejava.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 35656@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);

        // Get the process ID representing the running Java virtual machine.
        // Since JDK 10.
        pid = ManagementFactory.getRuntimeMXBean().getPid();
        System.out.println("PID = " + pid);

    }
}

Here is the result of the code above:

Name = 35656@Krakatau
PID  = 35656
PID  = 35656