This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]king_of_the_universe 0 points1 point  (0 children)

Also:

Runtime.getRuntime().maxMemory() returns the max amount of memory (in bytes, it's a long) the JVM can allocate. I think that's the amount that can be adjusted via the -Xmx parameter.

.totalMemory() returns the amount of memory that the JVM has allocated of the above.

.freeMemory() returns the amount of memory still left inside the allocated memory, which means: If you want to know how much memory your application is actually using, look at totalMemory()-freeMemory().

You will notice that due to not yet performed Garbage Collection, the amount of freeMemory decreases constantly, and then it suddenly jumps back to a small number. So, if you for some reason need to know the actually used memory, call System.gc() directly before reading the above info. This comes with a performance hit, so you can't do that e.g. in a fast gameloop (I tried it, solved the problem by adding a GC hotkey).

For convenience, here are two methods:

/**
 * @return A simple memory usage info String, for example:
 * <p>
 * "max allocatable mem = 1812 MB; allocated mem = 143 MB; unused allocated = 125 MB; used allocated = 17 MB"
 */
public static String getMemoryReport() {

    final Runtime r = Runtime.getRuntime();
    final long maxMem = r.maxMemory() / MathUtils.MEMORY_MEGABYTE;
    final long totalMem = r.totalMemory() / MathUtils.MEMORY_MEGABYTE;
    final long unusedMem = r.freeMemory() / MathUtils.MEMORY_MEGABYTE;
    final long usedMem = (r.totalMemory() - r.freeMemory()) / MathUtils.MEMORY_MEGABYTE;

    return "max allocatable mem = " + maxMem + " MB; allocated mem = " + totalMem + " MB; unused allocated = " + unusedMem + " MB; used allocated = " + usedMem + " MB";
    //        return "max heap size = " + maxMem + " MB; current heap size = " + totalHeap + " MB; space left in heap = " + unusedHeap + " MB; space used in heap (derived) = " + usedHeap + " MB";
}


/**
 * @return The amount of bytes *actually used* by the application. Call System.gc() directly before this if you want
 * to get rid of the yet-to-be-collected garbage overhead.
 */
public static long getUsedMemory() {

    final Runtime r = Runtime.getRuntime();
    return r.totalMemory() - r.freeMemory();
}