I am learning the memory management concepts in java. As per my understanding if I create a short life object which is referenced through a long life object then it will lead to memory leak.
I create a small program to verify this. I consciously created a class where one method would lead to memory leak and another method would not. I see that after the execution of both methods leads to ambiguous results.
The result is:
Used memory when no memory leak::10MB
Used memory when memory leak::9MB
I expected the first value to be much less than 2nd value
When were you expecting the garbage collector to run?
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Joined: Apr 17, 2011
It can run at any time. I was expecting that after the MemoryLeak.createNoMemoryleak() method would be called the used memory would be close to zero(as all the variables are method scoped and thus stored in stack.
When the NoMemoryLeak.createMemoryLeak() runs then the used memory value will be higher as I have assigned the objects to instance variables.
Do you mean to say that the used memory will go down only when gc runs irrespective of whether there are referenced or unreferenced objects.
Joined: Apr 17, 2011
Thanks for asking the question. It set me thinking and I called System.gc() immediately after the method call and now it shows me expected output.
The trace with changed code is
Used memory when no memory leak::0 MB
Used memory when memory leak::4 MB
There's nothing like a memory leak here. Note that all one million cells of the ArrayList contain a reference to the sameString object, and a million references to a single string take exactly the same amount of memory as a million null references -- about 4MB on a 32-bit JVM. Your 4MB is just from allocating that ArrayList.
Now if you changed add("TEST") to add(new String("TEST")), then you'd use a lot of memory, although I still wouldn't call it a leak, just a list full of strings.