Memory Analysis and Garbage Collection Confusion

So I’m doing some memory leak checks

I always print the amount of RAM I have supposedly used onto the screen, in MB:

ram_occupied = (int)(Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory())/1024/1024;

always trusted this is correct.

now it build up after time, gc makes it lower sometimes, all fine and good.

so now I want to do some analysis, I use Eclipse’s Memory Analyzer and “Acquire Heap Dump”, right
however the heap dump is only 3.4 MB of size - not telling me much, while I thought I had accumulated like 70 MB by now, as told by the code above

this btw also applies to jvisualvm and such

if I run the GC manually by using the button in visual vm for example, used ram shrinkes to about 4MB, from for example 70MB

this leds me to believe that the reason is, that most of it (66 MB) is just junk and not dump @ heap dump therefore - and stuff I don’t need to care about

my ram usage climbs 1-2MB per second on average, I use G1GC, and it can clean up until like 4MB - it doesnt always clean up everything, due to G1 I guess

Isn’t it just memory used by the VM? Eclipse might also be skipping memory that your code doesn’t allocate, like stuff Java automatically allocates for you on startup or something.

I believe the heap dump is a walk of live objects - it won’t give you the garbage.

Cas :slight_smile:

no. no. no. :emo:

ram_occupied = (int)(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1024/1024;

note the tiny change.

well my Xms and Xmx are always equal.

so “total” returns less (122MB for example) than “max” (128MB which is equivalent to the -Xms128m -Xmx128m I specify)
Reading the Javadoc doesn’t make it all clear to me, but I guess “total” doesn’t include memory the jvm uses by itself (unrelated to my code), while “max” just shows the whole 128

although I read that [quote]If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.
[/quote]

That may have long been the case, but recent JVMs are able to shrink the heap (eventually) to a value lower than you started with.