What is the exact meaning of Runtime.getRuntime().totalMemory()

来源:互联网 发布:数控雕刻机怎么编程 编辑:程序博客网 时间:2024/06/07 16:06

来源:http://stackoverflow.com/questions/3571203/what-is-the-exact-meaning-of-runtime-getruntime-totalmemory-and-freememory


               

According to the API

totalMemory()

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment.Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

In reference to your question, maxMemory() returns the -Xmx value.

You may be wondering why there is a totalMemory() AND a maxMemory().  The answer is that the JVM allocates memory lazily.  Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory.  totalMemory() corresponds to the amount of memory currently available to the JVM for Foo.  If the JVM needs more memory, it will lazily allocate it up to the maximum memory.  If you run with -Xms1024m -Xmx1024m, the value you get fromtotalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();



0 0