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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Trending

  • Agile Metrics and KPIs in Action
  • Send Your Logs to Loki
  • Effective Tips for Debugging Complex Code in Java
  • How To Verify Database Connection From a Spring Boot Application

Retrieving JMX information programmatically

Gabriel Dimech user avatar by
Gabriel Dimech
·
Jul. 16, 14 · Interview
Like (0)
Save
Tweet
Share
29.76K 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}

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

Opinions expressed by DZone contributors are their own.


Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: