Q:

Java: inaccurate result when calculating memory usage

I'd like to calculate the current memory usage of my java application. However, when I am using the following code, there is a substantial difference to what is shown in the task manager. 
Runtime rt = Runtime.getRuntime();
long usedMemory = (rt.totalMemory() - rt.freeMemory()) / 1024;

When, according to the task manager, the process consumes 3.000.000 K, this code will e.g. calculate 2.015.203 and one second later 1.712.296, when in fact memory usage has grown. 
According to similar questions, the code should be fine, but why is there such a huge difference compared to the task manager?

A:

The TaskManager tells you all the available memory for the java process (the JVM).
Internally, the JVM manages this memory as the program demands (so, there is "free" memory inside the JVM, but which appears as used to the TaskMan).
Also, the GC frees memory when it decides it is most useful. So, it is very possible that after creating more objects, the used memory is less because the GC has swept previously allocated (but unreachable) memory.

