List of running JVMs on the localhost

后端 未结 8 1380
慢半拍i
慢半拍i 2020-12-24 15:57

How to get in Java 6+ the list of running JVMs on the localhost and their specs (i.e. Java version, running threads, etc.)?

Does the Java API provide such features?

8条回答
  •  渐次进展
    2020-12-24 16:18

    You can actually get a list of JVMs using the Attach API, without resorting to using jconsole.jar.

    The following demonstrates getting the list of JVMs running locally, getting some properties, connecting to each via JMX, and getting some further information via that connection.

    // ...
    
    import com.sun.tools.attach.*;
    import javax.management.*;
    
    // ...
    
        List descriptors = VirtualMachine.list();
        for (VirtualMachineDescriptor descriptor : descriptors) {
            System.out.println("Found JVM: " + descriptor.displayName());
            try {
                VirtualMachine vm = VirtualMachine.attach(descriptor);
                String version = vm.getSystemProperties().getProperty("java.runtime.version");
                System.out.println("   Runtime Version: " + version);
    
                String connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
                if (connectorAddress == null) {
                    vm.startLocalManagementAgent();
                    connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
                }
    
                JMXServiceURL url = new JMXServiceURL(connectorAddress);
                JMXConnector connector = JMXConnectorFactory.connect(url);
                MBeanServerConnection mbs = connector.getMBeanServerConnection();
    
                ObjectName threadName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
                Integer threadCount = (Integer)mbs.getAttribute(threadName, "ThreadCount");
                System.out.println("    Thread count: " + threadCount);
            }
            catch (Exception e) {
                // ...
            }
        }
    

    A list of the available MXBeans is here. More on JMX in general can be found here, which I got from a comment on another answer to this question. Some code above came from both links.

    Note: For me at least, I had to add tools.jar to the bootstrap classpath for this to run:

    $ java -Xbootclasspath/a:${JAVA_HOME}/lib/tools.jar -jar 
    

提交回复
热议问题