How do I access memory usage programmatically via JMX?

You need to setup a JMXConnector. Here is a code snippet that will get the committed heap memory usage on a remote machine.

String host ="myHost";
int port = 1234;
HashMap map = new HashMap();
String[] credentials = new String[2];
credentials[0] = user;
credentials[1] = password;
map.put("jmx.remote.credentials", credentials);
JMXConnector c = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
c.connect();
Object o = c.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage");
CompositeData cd = (CompositeData) o;
System.out.println(cd.get("committed"));

private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException
{
    return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
}

If you don’t care about security you can set the map to null. You need to start up the remote server with;

-Dcom.sun.management.jmxremote.port=1234
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

You might want to take a look at wlshell which is a small utility that allows you to access MBeans on a remote server using a text interface or a script, It can be used with WebLogic, but it works for any Java program where you have enabled remote monitoring.

Leave a Comment