Java – How to get memory usage of tomcat 7 using JMX API

javajmxtomcat

Is it possible to get the memory usage statistics of a tomcat server using JMX API. Which Mbean can provide me this info? I am stuck at the formation of ObjectName in the below code

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2020/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url);
MBeanServerConnection server = jmxc.getMBeanServerConnection();

  Object o = jmxc.getMBeanServerConnection().getAttribute(
          new ObjectName("-----"); 

Wonder how jconsole draws the memory graphs, any pointers for the source code?

Best Answer

MBeanServer connection = ManagementFactory.getPlatformMBeanServer();
Set<ObjectInstance> set = connection.queryMBeans(new ObjectName("java.lang:type=Memory"), null);
ObjectInstance oi = set.iterator().next();
// replace "HeapMemoryUsage" with "NonHeapMemoryUsage" to get non-heap mem
Object attrValue = connection.getAttribute(oi.getObjectName(), "HeapMemoryUsage");
if( !( attrValue instanceof CompositeData ) ) {
    System.out.println( "attribute value is instanceof [" + attrValue.getClass().getName() +
            ", exitting -- must be CompositeData." );
    return;
}
// replace "used" with "max" to get max
System.out.println(((CompositeData)attrValue).get("used").toString());
Related Topic