Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"?
like image 891
einpoklum Avatar asked Feb 18 '13 13:02

einpoklum


1 Answers

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);
}
like image 191
BobTheBuilder Avatar answered Sep 30 '22 21:09

BobTheBuilder