Get the JVM peak memory usage

publish on

When monitoring the memory consumption of a Java application it can be useful to know what is the peak memory usage allocated by the JVM during the execution.

This code snippet used JVM Managed bean (as explained in monitoring JVM memory usage inside a java application blog post). To retrieve the peak memory usage during an execution you need to iterate through all MemoryPoolMXBean and call getPeakUsage():

package com.inoneo;


public static void main(String[] args){

    // Place this code just before the end of the program
    try {
        String memoryUsage = new String();
        List pools = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean pool : pools) {
            MemoryUsage peak = pool.getPeakUsage();
            memoryUsage += String.format("Peak %s memory used: %,d%n", pool.getName(),peak.getUsed());
            memoryUsage += String.format("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted());

        // we print the result in the console
   } catch (Throwable t) {
        System.err.println("Exception in agent: " + t);

comments powered by Disqus