While working on a project recently I need to find out the current process of the active running Java process (for tracing/auditing), however I never found a 100% perfect solution but did come across an acceptable solution to use the management classes to query its name, which happens to have encoding in it, so here is the quick solution:
import java.lang.management.ManagementFactory;
public class getpid
{
public static void main(String args[]) throws Exception
{
System.out.println("Process id : "+getProcessId());
}
public static long getProcessId()
{
String name = ManagementFactory.getRuntimeMXBean().getName();
String[] nameBits = name.split("@");
return nameBits == null ? -1 : Long.valueOf(nameBits[0]);
}
}
$ java getpid
Process id : 377