Getting Java VisualVM data from the command line

user2869231 picture user2869231 · Sep 30, 2014 · Viewed 8.3k times · Source

I'll start off with saying that I have just about no experience with Java VisualVM. However, it contains the information that some developers would like to see. When I open it up for my application, it contains a graph for CPU, Memory, Classes, and Threads. I was wondering if there was a way you could grab that information from the command line. So, if the application was using up 250 MB of memory at the time of call, is there a command I could write that would return 250 MB? Likewise with the number of threads it is using?

The version I'm using is 1.7.0_51.

Thanks.

Answer

Victor picture Victor · Oct 1, 2014

VisualVM is just a client application that consumes information exposed by the JVM via JMX. If you want to develop a quick client application and then invoke it via command line, is very easy:

Open a connection to the JVM (note that it needs to have the JMX ports open) using a URL:

final JMXServiceURL jmxUrl = new JMXServiceURL(jmxServiceUrl);
final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl);
final MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection();

Then, use the MBeanServerConnection object to perform queries on the JMX Beans exposed by the JVM. Sample about memory:

ObjectName jvmMemory = new ObjectName("java.lang", "type", "Memory");           
CompositeData heapUsage = (CompositeData) mbsc.getAttribute(jvmMemory, "HeapMemoryUsage");
printer.print(String.valueOf(heapUsage.get("used")));
printer.print(String.valueOf(heapUsage.get("committed")));
printer.print(String.valueOf(heapUsage.get("max")));

You have a whole range of Mbeans to query. Use the JVisualVM to see what are those MBeans.

Update

For info on how to open the JMX ports, see this answer.