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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • How GitHub Copilot Helps You Write More Secure Code
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  1. DZone
  2. Coding
  3. Java
  4. Retrieving JMX information programmatically

Retrieving JMX information programmatically

By 
Gabriel Dimech user avatar
Gabriel Dimech
·
Jul. 16, 14 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
31.2K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!