Program for Java Mission Control for JVM Monitoring
Now we will write a Java program to monitor CPU usage by performing CPU-intensive operations in a loop. The program should iterate for a specified number of times and print the CPU usage iteration number at each iteration. And, the program should include a short delay to reduce CPU load between iterations.
Below is the program to demonstrate Java Mission Control for JVM Monitoring:
// Java Program to demonstrate Java Mission Control
// for JVM Monitoring
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;
// Driver Class
public class GFG {
// Main Function
public static void main(String[] args)
throws InterruptedException {
// Start monitoring CPU usage using
// the Java Mission Control (JMC)
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long startCpuTime = threadMXBean.getCurrentThreadCpuTime();
int iteration = 0;
while (iteration < 10) {
// Perform some CPU-intensive operation
int sum = 0;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
// Print output at each iteration
System.out.println("CPU usage iteration: " + iteration);
// Add a short delay to reduce CPU load
TimeUnit.MILLISECONDS.sleep(100);
iteration++;
}
// Stop monitoring CPU usage
long endCpuTime = threadMXBean.getCurrentThreadCpuTime();
long cpuUsageMs = TimeUnit.NANOSECONDS.toMillis(endCpuTime - startCpuTime);
System.out.println("Total CPU usage: " + cpuUsageMs + " milliseconds");
}
}
Output :
Below we can refer the output image for better understanding.
Explanation of the above Program:
- Initialize a loop to iterate a specified number of times.
- Within the loop, perform a CPU-intensive operation, such as calculating the sum of integers up to Integer.MAX_VALUE.
- Print the CPU usage iteration number at each iteration.
- Add a short delay using Thread.sleep() to reduce CPU load between iterations.
- Increment the iteration counter.
- Continue the loop until the specified number of iterations is reached.
- After completing all iterations, end the program.
Introduction to Java Mission Control for JVM Monitoring
Java Mission Control (JMC) is a powerful monitoring, diagnostics, and performance analysis tool. Oracle provides this to run the Java applications on the Java Virtual Machine. It is part of the Java Development Kit and offers developers and administrators insights into the runtime behaviour of Java applications. The JMC is useful for identifying performance and other issues affecting the application’s efficiency.
Contact Us