3

When I run jconsole it shows me a list of Java processes:

enter image description here

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?

Kshitiz Sharma
  • 17,947
  • 26
  • 98
  • 169

2 Answers2

3

This article shows how to do it using Attach API from JDK tools.jar

kostya
  • 9,221
  • 1
  • 29
  • 36
1

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:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/tools/jps/Jps.java?av=f

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:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataFile.java

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.

Community
  • 1
  • 1
eugene-nikolaev
  • 1,290
  • 1
  • 13
  • 21