List of running JVMs on the localhost

后端 未结 8 1345
慢半拍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:20

    You can use jps, a command-line tool distributed with the jvm. I'm not aware of any normal Java API for it, though. However, JConsole can do what you ask, so I had a look at its source. It was quite scary, but while looking around I found references to the jVisualVM classes, which are OK seeing as you specify Java 6+. Here's what I found:

    The classes are all in sun.tools, so firstly you have to find the jconsole.jar that came with your JVM (assumes Sun JVM, of course) and add it to your classpath. Then a quick-n-dirty listing of the active VMs can be got like:

    public static void main(final String[] args) {
        final Map virtualMachines = LocalVirtualMachine.getAllVirtualMachines();
        for (final Entry entry : virtualMachines.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue().displayName());
        }
    }
    

    Once you've got a reference to your JVMs, you can communicate with them using the Attach API.

提交回复
热议问题