防止JAVA程序重复启动进程的解决办法

        今天看见一个同事为防止JAVA程序重复启动而烦恼,突然想到JDK自带工具JConsole的新建连接画面好像显示有所有JAVA进程的PID和启动时JAVA类的名称。如果能够取得启动类的全名,不就可以防止重复启动了吗。

       于是上CSDN下载了一个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));
            }
        }
    }


 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值