6

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?

michael667
  • 3,241
  • 24
  • 32

4 Answers4

7

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
amit
  • 175,853
  • 27
  • 231
  • 333
5

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

MaxMemory() is the value set by Xmx parameter

Nike
  • 312
  • 1
  • 2
  • 9
0

totalMemory() which represent current heap size of JVM which is combination of used memory currently occupied by objects and free memory available for new objects.As per javadoc value returned by totalMemory() may vary over time depending upon environment. JVM totalMemory also equals to initial heap size of JVM

maximum heap space is not going to change over JVM life cycle.Jvm always trying to expand the size of totalMemory() according to no of new object created But not beyond maxMemory() size unles we will get java.lang.OutOfMemoryError.

  • "may vary over time" more or less says that "equals initial heap size" is unlikely to be reliable in the general case. – Gus Nov 03 '16 at 02:47