How to check if a Java Process is running on any local Virtual Machine programmatically

Quick and dirty way to check if a Java Process is already running.
Useful if you need to run cronjobs periodically and you don’t know how long they might take, you can add this check at the beginning of your main, and it’ll look for all the local virtual machines that have a main class named like the “processName” string passed to it.

In other words, a quick and dirty programatic jps-like function you can add to your util toolset.

[java]
public static boolean isJavaProcessRunning(String processName) {
boolean result = false;

try {
HostIdentifier hostIdentifier = new HostIdentifier(“local://localhost”);
MonitoredHostProvider hostProvider = new MonitoredHostProvider(hostIdentifier);

MonitoredHost monitoredHost;
try {
monitoredHost = MonitoredHost.getMonitoredHost(hostIdentifier);
} catch (MonitorException e1) {
e1.printStackTrace();
return false;
}

Set activeVms = (Set) monitoredHost.activeVms();
int thisProcessCount = 0;
for (Integer activeVmId : activeVms) {
try {
VmIdentifier vmIdentifier = new VmIdentifier(“//” + String.valueOf(activeVmId) + “?mode=r”);
MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmIdentifier);
if (monitoredVm != null) {
String mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);
if (mainClass.toLowerCase().contains(processName.toLowerCase())) {
thisProcessCount++;
if (thisProcessCount > 1) {
result = true;
break;
}
}
}

} catch (MonitorException e) {
e.printStackTrace();
}
}

} catch (URISyntaxException e) {
e.printStackTrace();
} catch (MonitorException e) {
e.printStackTrace();
}

return result;
}
[/java]

Enjoy

One thought on “How to check if a Java Process is running on any local Virtual Machine programmatically

  1. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment.

    Is there any way you can remove me from that service?
    Cheers!

Leave a Reply

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