Monitor’ing Java processes can be achieved using the jvmstat monitor classes provided in the JVM. The documentation is a bit sketchy but with a little experimenting it can be done.
Below is a little example that shows you how to get a list of active Java processes.. which of course can then be used for other things 🙂
Here’s the code…
import java.net.URISyntaxException;
import java.util.Set;
import sun.jvmstat.monitor.*;
public class sjps
{
public static void main(String[] args)
throws MonitorException, URISyntaxException
{
MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost("localhost");
Set
for (int psId : activeVms)
{
MonitoredVm monitoredVm = monitoredHost.getMonitoredVm
(new VmIdentifier(String.valueOf(psId)));
String mainClass = MonitoredVmUtil.mainClass(monitoredVm, false);
String vmVersion = MonitoredVmUtil.vmVersion(monitoredVm);
String commandLine = MonitoredVmUtil.commandLine(monitoredVm);
System.out.println(mainClass + " [" + psId + "]" +
" using : "+vmVersion);
System.out.println(" -> "+commandLine);
}
}
}
And to see the code running..
$ java sjps
sjps [865] using : 14.1-b02-90
-> sjps
JConsole [863] using : 14.1-b02-90
-> sun.tools.jconsole.JConsole