This code is designed to monitor the java heap space of a JVM. At times java applications get errored out due to lack of java heap space, so if there is any requirement of continuously monitoring the Java heap space(Old gen, perm Gen, Survivor Space etc) at a continuous interval(1 min) then this code can be used.
package com.mhe.soa.monitoring; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.Set; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.openmbean.CompositeDataSupport; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import com.mhe.soa.monitoring.MemoryObj; import com.mhe.soa.monitoring.ServerMemoryObj; import java.util.Date; import java.sql.Timestamp; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Calendar; public class JVMHeapMonitor { private static MBeanServerConnection connection=null; private static JMXConnector connector; private static HashMap serverMemoryMap = null; private static Properties properties = null; public final static String jndi_suffix = "/jndi/weblogic.management.mbeanservers.domainruntime"; public final static String jndi_prefix = "service:jmx:iiop://"; public static MBeanServerConnection getConnection() { if (connection==null) connect(); return connection; } private static ArrayList notifyThreshold(long threshold, String[] memoryTypes) throws Exception { Set mbeans = null; try { mbeans = getConnection().queryMBeans(new ObjectName( "java.lang:type=MemoryPool,*"), null); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); connection=null; notifyThreshold(threshold,memoryTypes); } Iterator iter = mbeans.iterator(); ObjectInstance objectInstance = null; int index1 = 0; while (iter.hasNext()) { index1++; objectInstance = (ObjectInstance) iter.next(); String gcCollectorName = objectInstance.getObjectName() .getCanonicalKeyPropertyListString(); //System.out.println("objectInstance.getObjectName()"+objectInstance.getObjectName()); // System.out.println("##############"+objectInstance.getObjectName().getCanonicalKeyPropertyListString()); if (!checkMemoryTypes(gcCollectorName, memoryTypes)) continue; ObjectName memoryManagerMXBean = null; try { memoryManagerMXBean = new ObjectName("java.lang:" + gcCollectorName); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } CompositeDataSupport dataSenders = null; try { dataSenders = (CompositeDataSupport) getConnection().getAttribute( memoryManagerMXBean, "Usage"); } catch (AttributeNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); connection=null; notifyThreshold(threshold,memoryTypes); } if (dataSenders != null) { String serverName = objectInstance.getObjectName() .getKeyProperty("Location"); System.out.println("ServerName : "+serverName); String memoryType = objectInstance.getObjectName() .getKeyProperty("name"); System.out.println("MemoryType : "+memoryType); Long commited = (Long) dataSenders.get("committed"); System.out.println("commited : "+commited); Long init = (Long) dataSenders.get("init"); System.out.println("init : "+init); Long max = (Long) dataSenders.get("max"); System.out.println("max : "+max); Long used = (Long) dataSenders.get("used"); System.out.println("used : "+used); Long percentage = ((used * 100) / max); System.out.println("percentage : "+percentage); MemoryObj memoryObj = new MemoryObj(memoryType, commited, init, max, used, percentage); add(serverName, memoryObj); } } JVMDataFileGenerator fileGen= new JVMDataFileGenerator(); fileGen.generateDataFile(getServerMemoryMap()); //ins.insertJVMDataIntoDB(getServerMemoryMap()); ArrayList list = matchThreshold(threshold); return list; } private static boolean checkMemoryTypes(String memoryPool, String[] memoryTypes) { for (int index = 0; index < memoryTypes.length; index++) { if (memoryPool.indexOf(memoryTypes[index]) != -1) return true; } return false; } private static void add(String serverName, MemoryObj memoryObj) { ServerMemoryObj serverMemoryObj = null; if (getServerMemoryMap().get(serverName) == null) { serverMemoryObj = new ServerMemoryObj(serverName); getServerMemoryMap().put(serverName, serverMemoryObj); } else serverMemoryObj = (ServerMemoryObj) getServerMemoryMap().get( serverName); serverMemoryObj.add(memoryObj); } private static HashMap getServerMemoryMap() { if (serverMemoryMap == null) serverMemoryMap = new HashMap(); return serverMemoryMap; } private static ArrayList matchThreshold(long percentage) { ArrayList list = new ArrayList(); ServerMemoryObj serverMemoryObj = null; Set keys = getServerMemoryMap().keySet(); Iterator iterator = keys.iterator(); String key = null; while (iterator.hasNext()) { key = (String) iterator.next(); serverMemoryObj = (ServerMemoryObj) getServerMemoryMap().get(key); if (serverMemoryObj.matchThreshold(percentage)) list.add(serverMemoryObj); } return list; } private static void waitme() { byte[] input = null; try { while (true) { System.out .println("\n\tWaiting for Notifications (Press Anykey to Exit). ........"); System.in.read(input); if (new String(input).equals("quit")) break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void connect() { String hostname = properties.getProperty("wl_host"); String port = properties.getProperty("wl_port"); String user = properties.getProperty("wl_user"); String password = properties.getProperty("wl_password"); JMXServiceURL serviceUrl = null; try { serviceUrl = new JMXServiceURL(jndi_prefix + hostname + ":" + port + jndi_suffix); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Connecting to: " + serviceUrl); Hashtable env = new Hashtable(); env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, user); env.put(javax.naming.Context.SECURITY_CREDENTIALS, password); try { connector = JMXConnectorFactory.newJMXConnector(serviceUrl, env); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { connector.connect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { connection = connector.getMBeanServerConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws Exception { try { properties = new Properties(); System.out.println("trying to load properties"); System.out.println("args[0] is : "+args[0]); properties.load(new FileInputStream(args[0])); System.out.println("loaded prop file"); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("2"); System.exit(0); e.printStackTrace(); } try { long waitTime = Long.parseLong((String) properties.get("interval")); long threshold = Long.parseLong((String) properties .get("Threshold")); // String[] memoryTypes = new String[] { "PS Old Gen", "PS Perm Gen" }; String[] memoryTypes = new String[] { "PS Old Gen", "PS Perm Gen","PS Survivor Space","PS Eden Space" }; while (true) { serverMemoryMap = new HashMap(); long startTime = System.currentTimeMillis(); ArrayList serverList = notifyThreshold(threshold, memoryTypes); long endTime = System.currentTimeMillis(); long duration = (endTime - startTime); System.out.println("Processing Time:" + duration); System.out.println("Sleeping for " + waitTime + " seconds"); Thread.sleep(waitTime * 1000); } } finally { if (connector != null) connector.close(); } } }