File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Memory leak Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Memory leak" Watch "Memory leak" New topic
Author

Memory leak

Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 108
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

Joined: Sep 20, 2010
Posts: 3647
    
  17

When were you expecting the garbage collector to run?
Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 108
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

Joined: Apr 17, 2011
Posts: 108
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

A leak is only a leak when it's unintended
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Memory leak