Naman
Naman

Reputation: 2669

How to get all garbage collector MX beans in java of a remote jmx URL?

I am having a jmx remote url and I want to get all GC related information that it has exposed through jmx. I am using following code :

MBeanServerConnection conn = getMBeanServerConnection(url);
        if (conn != null)
            return ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE, GarbageCollectorMXBean.class);
return null;

The problem here is that I have not defined the name and only type, so it gives exception. So I defined name also as following : -

    return ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE+",name=PS MarkSweep", GarbageCollectorMXBean.class);

But here I have hard coded "PS MarkSweep". But the JVM might be using "ConcurrentMarkSweep". How can I get the list of all GC MBeans?

Upvotes: 2

Views: 2101

Answers (1)

Nicholas
Nicholas

Reputation: 16066

You can do this by issuing an MBean query against the MBeanServerConnection as follows:

MBeanServerConnection mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> gcnames = mbs.queryNames(new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=*"), null);
Set<GarbageCollectorMXBean> gcBeans = new HashSet<GarbageCollectorMXBean>(gcnames.size());
for(ObjectName on: gcnames) {
    gcBeans.add(ManagementFactory.newPlatformMXBeanProxy(mbs, on.toString(), GarbageCollectorMXBean.class));
}

Now the gcBeans set is loaded with one GarbageCollectorMXBean per Garbage Collector.

Upvotes: 6

Related Questions