When to use Runtime.maxMemory() and totalMemory() [duplicate]
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?
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.
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.
MaxMemory() is the value set by Xmx parameter
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.
精彩评论