When I run jconsole
it shows me a list of Java processes:
I could then connect to one of these and see its MBeans
. How does it discover the JMX processes? How can I do this in a program?
When I run jconsole
it shows me a list of Java processes:
I could then connect to one of these and see its MBeans
. How does it discover the JMX processes? How can I do this in a program?
Replying since I had this question too and got an answer. There is a JPS program in JDK which shows java processes. I am not 100% sure (don't want to dive deep into jconsole code) but 99% sure jconsole uses the same mechanism as jps:
HostIdentifier hostId = arguments.hostId();
MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(hostId);
// get the set active JVMs on the specified host.
Set<Integer> jvms = monitoredHost.activeVms();
These class are part of tools.jar, you need to include it in the project's classpath.
If we go deeper (I do not expose all the intermediate steps) - finally we'll know that active VMs list is populated from hsperfdata files in temporary directories:
Here is a link to know more: java hsperfdata directory
At last, here is a code snippet allowing you to get the java processes ids:
sun.jvmstat.monitor.MonitoredHost host = sun.jvmstat.monitor.MonitoredHost.getMonitoredHost(new sun.jvmstat.monitor.HostIdentifier((String) null));
System.out.println(host.activeVms());
P.S.
Then you can use Attach API (as kostya mentioned) to discover the rest of needed things.