JMX Code to print peak Native Memory Usage and Code Cache

This code can be used to print the native usage of a JVM and also the code cache usage. To get the details we need to enable JMX on the server by following the steps below. We need to enable -XX:NativeMemoryTracking=detail flag as well.

<code>import java.io.IOException;
import java.net.MalformedURLException;

import javax.management.openmbean.*;
import javax.naming.*;
import javax.management.*;
import javax.management.remote.*;
import java.util.*;
import javax.management.ObjectName.*;
import weblogic.management.mbeanservers.*;
import weblogic.management.configuration.*;
import weblogic.health.HealthState;
import java.net.*;
import java.io.InputStream;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;


public class HeapMonitor {
 private static MBeanServerConnection connection;
 private static JMXConnector connector;

 public static void main(String args[]) {



  try {
   JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://stage2cpp094.qa.paypal.com:8888/jmxrmi");
   JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
   jmxc.connect();
   System.out.println("Connection successfull");




   Object memoryMbean = null;
   CompositeData memoryMbeanCd = null;

   Object codeCacheMbean = null;
   CompositeData codeCacheMbeanCd = null;

   jmxc.getMBeanServerConnection().invoke(new ObjectName("java.lang:type=Memory"), "gc", null, null);

   memoryMbean = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage");
   memoryMbeanCd = (CompositeData) memoryMbean;

   System.out.println("Max Native Memory Usage: " + " " + memoryMbeanCd.get("max"));

   codeCacheMbean = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Code Cache"), "PeakUsage");

   codeCacheMbeanCd = (CompositeData) codeCacheMbean;

   System.out.println("Peak Code Cache Usage: " + " " + codeCacheMbeanCd.get("max"));



  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}</code>

Leave a Reply