[Java] How to get Process Id from java program

It’s common to get pid or process id using top or ps command. Sometime we have a need that get the pid from within java code. How do we do it? JMX comes to the rescue. The information is available as part RuntimeMXBean. Following is the code snippet that can get the pid

public static String getPid() {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    return name.substring(0, name.indexOf("@"));
}

The format is pid@hostname. Using substring, we get the pid of the JVM process

Leave a Reply

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