今天看见一个同事为防止JAVA程序重复启动而烦恼,突然想到JDK自带工具JConsole的新建连接画面好像显示有所有JAVA进程的PID和启动时JAVA类的名称。如果能够取得启动类的全名,不就可以防止重复启动了吗。
于是上优快云下载了一个JConsole的源代码。发现在sun.tools.jconsole.LocalVirtualMachine有实现类似功能的代码,摘录如下:(是不是正的可以防止重复启动还有待实证,此处暂记下解决思路)
private static void getMonitoredVMs(Map<Integer, LocalVirtualMachine> map) {
MonitoredHost host;
Set vms;
try {
host = MonitoredHost.getMonitoredHost(new HostIdentifier((String)null));
vms = host.activeVms();
} catch (java.net.URISyntaxException sx) {
throw new InternalError(sx.getMessage());
} catch (MonitorException mx) {
throw new InternalError(mx.getMessage());
}
for (Object vmid: vms) {
if (vmid instanceof Integer) {
int pid = ((Integer) vmid).intValue();
String name = vmid.toString(); // default to pid if name not available
boolean attachable = false;
String address = null;
try {
MonitoredVm mvm = host.getMonitoredVm(new VmIdentifier(name));
// use the command line as the display name
// 注:此处取得该进程的启动类全名
name = MonitoredVmUtil.commandLine(mvm);
attachable = MonitoredVmUtil.isAttachable(mvm);
address = ConnectorAddressLink.importFrom(pid);
mvm.detach();
} catch (Exception x) {
// ignore
}
map.put((Integer) vmid,
new LocalVirtualMachine(pid, name, attachable, address));
}
}
}