What are Runtime.getRuntime().totalMemory() and freeMemory()?
I've been wondering what the exact meaning of Runtime.ge开发者_如何学编程tRuntime().totalMemory(), Runtime.getRuntime().freeMemory(), and Runtime.getRuntime().maxMemory() is.
My understanding is, Runtime.getRuntime().totalMemory()
returns the total memory my process is using. Is that correct?
How about freeMemory()
and maxMemory()
?
The names and values are confusing. If you are looking for the total free memory you will have to calculate this value by your self. It is not what you get from freeMemory();
.
See the following guide:
Total designated memory, this will equal the configured -Xmx value:
Runtime.getRuntime().maxMemory();
Current allocated free memory, is the current allocated space ready for new objects. Caution this is not the total free available memory:
Runtime.getRuntime().freeMemory();
Total allocated memory, is the total allocated space reserved for the java process:
Runtime.getRuntime().totalMemory();
Used memory, has to be calculated:
usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Total free memory, has to be calculated:
freeMemory = Runtime.getRuntime().maxMemory() - usedMemory;
A picture may help to clarify:
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 from totalMemory()
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();
To understand it better, run this following program (in jdk1.7.x) :
$ java -Xms1025k -Xmx1025k -XshowSettings:vm MemoryTest
This will print jvm options and the used, free, total and maximum memory available in jvm.
public class MemoryTest {
public static void main(String args[]) {
System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory() + " bytes");
System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory() + " bytes");
System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory() + " bytes");
}
}
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.
Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.
Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.
JVM heap size can be growable and shrinkable by the Garbage-Collection mechanism. But, it can't allocate over maximum memory size: Runtime.maxMemory. This is the meaning of maximum memory. Total memory means the allocated heap size. And free memory means the available size in total memory.
example) java -Xms20M -Xmn10M -Xmx50M ~~~. This means that jvm should allocate heap 20M on start(ms). In this case, total memory is 20M. free memory is 20M-used size. If more heap is needed, JVM allocate more but can't over 50M(mx). In the case of maximum, total memory is 50M, and free size is 50M-used size. As for minumum size(mn), if heap is not used much, jvm can shrink heap size to 10M.
This mechanism is for efficiency of memory. If small java program run on huge fixed size heap memory, so much memory may be wasteful.
You can see the results in MB format, with the division of 1024 x 1024 which is equal to 1 MB.
int dataSize = 1024 * 1024;
System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/dataSize + " MB");
System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory()/dataSize + " MB");
System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory()/dataSize + " MB");
System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory()/dataSize + " MB");
精彩评论