Quantcast
Channel: Gubatron.com
Viewing all articles
Browse latest Browse all 165

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

$
0
0

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


Viewing all articles
Browse latest Browse all 165

Latest Images

Trending Articles





Latest Images