Retrieving the Process ID (PID) in Java

Sometimes it is necessary for a Java application to retrieve it’s own process id. An example of where this could be required is for logging/debugging purposes. Below is a simple “Java way” (there are other ways to discover the process id but they are more complex and require JNI or some shell scripting) to retrieve the process id:


import java.lang.management.ManagementFactory;

public class ApplicationPID {

public static void main(String [] args){
String name = ManagementFactory.getRuntimeMXBean().getName();
System.out.println("Process ID for this app = " + name);
}
}

This is the output:

Process ID for this app = 2584@MyComp

As you would have noticed from the snippet above, we have used the method: RuntimeMXBean.getName().

However, there is a caveat. As per the Javadoc, this method is JVM implementation dependent. Different implementations of JVM might return different results. Because of this limitation, we cannot use a standard parsing logic to do some automated processing on the PID.
I have tested this on SUN’s JVM, and found it to be working fine.

Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

Advertisements
This entry was posted in Java and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s