How to get memory usage of tomcat 7 using JMX API?

11,184

Solution 1

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());

Solution 2

code snippet for getting used memory for local/remote tomcat :

 JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://{remote ip/localhost}:2020/jmxrmi");
      JMXConnector jmxc = JMXConnectorFactory.connect(url);
      MBeanServerConnection server = jmxc.getMBeanServerConnection();
      Object o = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage");
      CompositeData cd = (CompositeData) o;
      System.out.println(cd.get("used"));

Solution 3

sample code

List memBeans = // get list of mbeans for (Iterator i = memBeans.iterator(); i.hasNext(); ) {

MemoryPoolMXBean mpool = (MemoryPoolMXBean)i.next();
MemoryUsage usage = mpool.getUsage();

String name = mpool.getName();      
float init = usage.getInit()/1000;
float used = usage.getUsed()/1000;
float committed = usage.getCommitted()/1000;
float max = usage.getMax()/1000;
float pctUsed = (used / max)*100;
float pctCommitted = (committed / max)*100;

}

here and here are some links which can help

Share:
11,184
sanre6
Author by

sanre6

:)

Updated on June 13, 2022

Comments

  • sanre6
    sanre6 almost 2 years

    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?

  • sanre6
    sanre6 about 12 years
    how to get the list of mbeans i can only see getDomains() in MBeanServerConnection class
  • sanre6
    sanre6 about 12 years
    the above code is returning me a constant metric from jvm , not application wise
  • sanre6
    sanre6 about 12 years
    i understood your code after reading about composite datatype , thanks