JMX Code to print peak Native Memory Usage and Code Cache

The below code can be used to monitor the non heap usage of the JVM. You can use this code to find out the peak code cache usage after load and performance testing and set the value accordingly in live. Its also useful in scenarios in which you are observing high utilization of non native memory and you need to understand the breakdown of it.

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://xxxxxxx: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();
  }

 }

}