Tracking memory usage
You're working on a data processing application that manipulates large collections of objects. Implement a memory monitoring utility that helps track memory consumption during critical operations to prevent OutOfMemoryError
exceptions.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Retrieve the current JVM runtime instance.
- Using the runtime total memory and free memory calculate the currently used memory.
- Call the method to retrieve the used memory in megabytes.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
public static double getUsedMemoryMB() {
// Retrieve the JVM runtime instance
Runtime runtime = ____
// Calculate the current used memory
long usedMemoryBytes = runtime.____ - runtime.____;
return usedMemoryBytes / (1024.0 * 1024.0);
}
public static void main(String[] args) {
double memoryBefore = getUsedMemoryMB();
System.out.println("Memory before array creation: " + memoryBefore + " MB");
int size = 10_000_000;
double[] largeArray = new double[size];
for (int i = 0; i < size; i++) {
largeArray[i] = Math.sqrt(i);
}
// Get the currently used memory in megabytes
double memoryAfter = ____;
System.out.println("Memory after array creation: " + memoryAfter + " MB");
System.out.println("Memory used by array creation: " + (memoryAfter - memoryBefore) + " MB");
}
}