For some reason ”getPid()” Bug Parade entry has been hanging for ever ”in progress, won’t ever fix” state.
However, after quick searching there is workaround, which hopefully works in ”major” cases (meaning Linux, M$windows and OSX).
NOTE: Tested logic only in Linux box. However, since logic relies into public API, it should be working in other OS also.
[code lang=”java”]
/**
* Get current process PID
*
* @return pid, -1 if resolving failed
*/
public static int getPID() {
int pid = -1;
try {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String id = runtime.getName();
int idx = id.indexOf(’@’);
if (idx != -1) {
id = id.substring(0, idx);
}
pid = Integer.parseInt(id);
} catch (Exception e) {
LOG.warn(”Failed to resolve PID”, e);
}
return pid;
}
[/code]
So we get current process PID. Next question is what we could do with such information.
And here comes one answer…
We could, for example, include $JDK_HOME/lib/tools.jar into classpath of our application, and then perform following:
[code lang=”java”]
public static void dumpHeap(String pFilename) throws Exception {
int pid = SystemUtil.getPID();
String className = ”sun.tools.jmap.JMap”;
Class cls = Class.forName(className);
Class[] paramTypes = {String[].class};
String[] param = {
”-dump:format=b,file=” + pFilename,
”” + pid
};
Method method = cls.getDeclaredMethod(”main”, pParamTypes);
return method.invoke(null, new Object[]{param});
}
[/code]
This piece of code creates heap dump of current java process in HPROF format. Resulting dump can be then analyzed using jhat
utility delivered with Sun JDK 6.
References: