How can a Java program track the maximum actual heap size used at launch time?

I am running a specific Java program with its -Xmx higher than -Xms, i.e. her pile can grow. End-of-End Heap Size (IIRC) is not the maximum size used during a run.

  • How to get the current heap size?
  • How can I get the maximum heap size during a run, besides periodically polling the current size of "myself"?
+6
source share
5 answers

// Get the current heap size in bytes

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

// Get the maximum heap size in bytes. The heap cannot exceed this size. // Any attempt will throw an OutOfMemoryException.

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

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

 long heapFreeSize = Runtime.getRuntime().freeMemory(); 
+2
source

Get the 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); } 
+4
source

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

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

If you are comfortable checking the heap size outside of your program, you should use JVisualVM. You can find it in the bin folder of your JDK. Just run it and attach it to your java program to get an idea of ​​your use of a bunch of programs. It will display a graph of your heap usage, making it easy to find the maximum heap size for running your program.

+2
source

Other answers provide a runtime mechanism through Runtime.getRuntime (). totalMemory () and maxMemory (), but VERY careful - the answer will be correct only at the moment. After the GC, totalMemory () will change (down!). You cannot have an absolutely accurate idea of β€‹β€‹β€œhow many living objects exist in the system” always, since this is exactly what the GC calculates and is expensive.

Using JMX (see GC bean, etc.) will help with this survey, but again, this is a pattern over time.

So, I'm not sure what you are actually trying to solve here ...

+2
source

See runtime information:

 Runtime.getRuntime().maxMemory(); Runtime.getRuntime().totalMemory(); Runtime.getRuntime().freeMemory(); 
+1
source

All Articles