Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

tomcat

jmx

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?

like image 508
sanre6 Avatar asked Jan 18 '23 13:01

sanre6


1 Answers

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());
like image 167
mindas Avatar answered Jan 29 '23 11:01

mindas