Skip to content

Instantly share code, notes, and snippets.

@ricston-git
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricston-git/cd7c07ab2224f3d513bd to your computer and use it in GitHub Desktop.
Save ricston-git/cd7c07ab2224f3d513bd to your computer and use it in GitHub Desktop.
jmxClient
// create jmx connection with mules jmx agent
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1098/server");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
jmxc.connect();
//create object instances that will be used to get memory and operating system Mbean objects exposed by JMX; create variables for cpu time and system time before
Object memoryMbean = null;
Object osMbean = null;
long cpuBefore = 0;
long tempMemory = 0;
CompositeData cd = null;
cpuBefore = Long.parseLong(a.toString());
// call the garbage collector before the test using the Memory Mbean
jmxc.getMBeanServerConnection().invoke(new ObjectName("java.lang:type=Memory"), "gc", null, null);
//create a loop to get values every second (optional)
for (int i = 0; i < samplesCount; i++) {
//get an instance of the HeapMemoryUsage Mbean
memoryMbean = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage");
cd = (CompositeData) memoryMbean;
//get an instance of the OperatingSystem Mbean
osMbean = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=OperatingSystem"),"ProcessCpuTime");
System.out.println("Used memory: " + " " + cd.get("used") + " Used cpu: " + osMbean); //print memory usage
tempMemory = tempMemory + Long.parseLong(cd.get("used").toString());
Thread.sleep(1000); //delay for one second
}
//get system time and cpu time from last poll
long cpuAfter = Long.parseLong(osMbean.toString());
long cpuDiff = cpuAfter - cpuBefore; //find cpu time between our first and last jmx poll
System.out.println("Cpu diff in milli seconds: " + cpuDiff / 1000000); //print cpu time in miliseconds
System.out.println("average memory usage is: " + tempMemory / samplesCount);//print average memory usage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment