Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Memory leak

 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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

Below is the program

 
Stephan van Hulst
Bartender
Pie
Posts: 5574
53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When were you expecting the garbage collector to run?
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stephan,
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

The changed code is
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing like a memory leak here. Note that all one million cells of the ArrayList contain a reference to the same String 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.
 
Stephan van Hulst
Bartender
Pie
Posts: 5574
53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A leak is only a leak when it's unintended
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic