Samuel Sjöberg's weblog

Skip to navigation

How to get the PID of the current JVM

At work, I needed to get the PID of the current JVM to be able to pass it to another JVM, which then would shut it down. After some googling and a bunch of failed attempts I ended up with this:

private int getProcessId() {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    StringBuffer pid = new StringBuffer();
    for (int i = 0, l = name.length(); i < l; i++) {
        if (Character.isDigit(name.charAt(i))) {
        } else if (pid.length() > 0) {
    try {
        return Integer.parseInt(pid.toString());
    } catch (NumberFormatException e) {
        return 0;

The RuntimeMXBean is available from Java 5 and allows you to fetch the name of the running JVM. Unfortunately its output isn't specified in the documentation, but Sun's JVM seems to return the following processId@machineId (e.g., 5575@blanco-local) on both Windows, Linux and OS X. This output, we can simply parse to get hold of a PID and that's what's being done in the sample code above.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 11th December 2006 20:32 CET. Filed under Java.

0 Pingbacks