Remote Monitoring Heap Memory Usage Using JMX RMI

Perhaps you want to record the memory usage of your application during runtime? Here is how to do it within java iself. Note that you won’t have to add code to your target application.

An example application that will be monitored using jmx/rmi:

package org.schueth.dummytest;

import java.util.ArrayList;

public class DummyApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		ArrayList<String> anyList = new ArrayList<String>();
		while (true) {
			Thread.sleep(100);
			anyList.add(random());
		}
	}

	public static String random() {
		StringBuffer s = new StringBuffer();
		int i = 0;
		while (i < 400) {
			s.append((char) (int) (Math.random() * 10 + 65));
			i++;
		}
		return s.toString();
	}

}

The application that will read the MemoryMXBean information:

package org.schueth.jmx;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class JMXTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		JMXServiceURL u = new JMXServiceURL(
				"service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
		JMXConnector c = JMXConnectorFactory.connect(u);
		MBeanServerConnection mbsc = c.getMBeanServerConnection();

		MemoryMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbsc,
				ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);

		while (true) {
			System.out.println(mbean.getHeapMemoryUsage());
			System.out.println(mbean.getNonHeapMemoryUsage());
			Thread.sleep(100);
		}

	}
}
  1. Start the DummyApp with the folling params using at least java 1.5:

java -D -Dcom.sun.management.jmxremote.authenticate=false  -Dcom.sun.management.jmxremote.port=9999  -Dcom.sun.management.jmxremote.ssl=false  -cp bin org.schueth.dummytest.DummyApp