DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • DuckDB for Python Developers
  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • Guess the Speed: Building a Family Internet Speed Guessing Game
  • How to Build Your Own AI SRE From Scratch

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Retrieving JMX information programmatically

Retrieving JMX information programmatically

By 
Gabriel Dimech
·
Jul. 16, 14 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
31.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Retrieving JMX information for a Java process is very easy when using a tool such as JConsole or JVisualVM. These provide an interface that allows viewing of information such as CPU usage, memory usage, threads active and more. This blog post gives an example of how to retrieve such information programmatically.

In order to retrieve JMX information from a Java application, the target application must be configured to expose JMX information. This link shows how to do this.

As an example, we shall be retrieving CPU and memory usage from a standalone Mule instance. In Mule, the JMX agent may be configured from a Mule configuration file. Through this, one may set the address that a JMX client can use to retrieve information; this is how.

The following Java code allows for polling the JMX agent and retrieving memory, CPU usage and also shows how to remotely invoke the garbage collector:

// 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

The above example prints:

...
Used memory: 23376624 Used cpu: 38060000000
Used memory: 24020624 Used cpu: 38080000000
Used memory: 24621920 Used cpu: 38090000000
Cpu diff in milli seconds: 4230
average memory usage is: 28028204

When the JMX agent may not be enabled for a Java process, it is also possible to retrieve information by fetching the process by id, for example. The following code shows how to do this using Sigar API:

//create a sigar object
Sigar sigar = new Sigar();
 
for (int i = 0; i < 100; i++) {
 
ProcessFinder find = new ProcessFinder(sigar);
//get the list of current java processes, and optionally query the list to choose which process to monitor
long[] pidList = sigar.getProcList();
//assuming we know the process id, we may query the process finder
long pid = find.findSingleProcess("Pid.Pid.eq=54730");
//get memory info for the process id
ProcMem memory = new ProcMem();
memory.gather(sigar, pid);
//get cou info for the oricess id
ProcCpu cpu = new ProcCpu();
cpu.gather(sigar, pid);
//print the memory used by the process id
System.out.println("Current memory used: " + Long.toString(memory.getSize()));
//print all memory info
System.out.println(memory.toMap());
//print all cpu info
System.out.println(cpu.toMap());
Thread.sleep(1000);
}

This is displayed when running the above example:

Current memory used: 3257659392
{Resident=258789376, PageFaults=109613, Size=3257659392}
{User=34973, LastTime=1404467787774, Percent=0.0, StartTime=1404467383826, Total=38121, Sys=3148}
Java (programming language)

Published at DZone with permission of Gabriel Dimech. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook