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

heap-memory, java, jvm, memory

Solution

// 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(); 

Problem

I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. - How can I get the current heap size? - How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?

Original source