Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Runtime.maxMemory() and totalMemory() [duplicate]

Tags:

java

What is the exact difference between Runtime.maxMemory() and Runtime.totalMemory()? The javadoc is quite vague about this (for me).

What are typical use cases for these two methods, that is, When would it be inappropriate to use the respective other one?

like image 449
michael667 Avatar asked Sep 29 '11 13:09

michael667


2 Answers

The totalMemory() returns how much memory is currently used, while the maxMemory() tells how much the JVM can allocate in total.

Note: that from this follows: totalMemory() <= maxMemory(), and you can also get 'how much memory is left' by maxMemory() - totalMemory()

One use case for this is to diagnose how much memory your program uses, and you'll use totalMemory() for it.
Note: both are referring only to heap memory, and not stack memory.

like image 187
amit Avatar answered Sep 21 '22 22:09

amit


The total memory is the memory that is currently allocated to the JVM. It varies over time. The max memory is the maximum memory that the JVM could ever reach. It's the upper limit of the total memory.

like image 32
JB Nizet Avatar answered Sep 21 '22 22:09

JB Nizet