How can a Java program keep track of the maximum actual heap size used during its run?

Get current heap size:

public static long getHeapSize(){
    int mb = 1024*1024;

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    return ((runtime.totalMemory() - runtime.freeMemory()) / mb);
}

If you want to inspect it from your program itself, use the methods of the Runtime class:

Runtime.getRuntime().freeMemory()
Runtime.getRuntime().maxMemory()

If it is ok for you to inspect the heap size from outside your program, you should use JVisualVM. You can find it in the bin folder of your JDK. Simply start it, and attach to your java program to get insight into your programs heap usage. It will display a graph of your heap usage, making it easy to find the maximum heap size of the run of your program.


// Get current size of heap in bytes

long heapSize = Runtime.getRuntime().totalMemory(); 

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.

long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.

long heapFreeSize = Runtime.getRuntime().freeMemory();