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

January 30th, 2013 5 minutes reading time.


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.

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<Integer> activeVms = (Set<Integer>) 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;
    }

Enjoy

Please Donate To Bitcoin Address: [[address]]

Donation of [[value]] BTC Received. Thank You.
[[error]]

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

  1. windsor kitchen chairs big lots Says:

    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