Solved

memory leak example

Posted on 2010-11-11
12
627 Views
Last Modified: 2012-05-10
hi guys

i got this peice of code from this link
http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/


public void leakingRequestLog(int iter) {
            Random requestQueue = new Random();
            for (int i=0; i<iter; i++) {
                  int newRequest = requestQueue.nextInt();
                  pendingRequests.add(new Integer(newRequest));
                  // processed request, but forgot to remove it
                  // from pending requests
            }
      }

      public void noLeak(int size) {
            HashSet tmpStore = new HashSet();
            for (int i=0; i<size; ++i) {
                  String leakingUnit = new String("Object: " + i);
                  tmpStore.add(leakingUnit);
            }
            // Though highest memory allocation happens in this
            // function, but all these objects get garbage
            // collected at the end of this method, so no leak.
      }

      public static void main(String[] args) throws IOException {
            LeakExample javaLeaks = new LeakExample();
            for (int i=0; true; i++) {
                  try { // sleep to slow down leaking process
                        Thread.sleep(1000);
                  } catch (InterruptedException e) { /* do nothing */ }
                  System.out.println("Iteration: " + i);
                  javaLeaks.slowlyLeakingVector(1000,10);
                  javaLeaks.leakingRequestLog(5000);
                  javaLeaks.noLeak(100000);
            }
      }


comparing leakingRequestLog method with noLeak method i dont understand the comments of the author
for leakingRequestLog method , the comment is  // processed request, but forgot to remove it from pending requests
and for noLeak method the comment is // Though highest memory allocation happens in this function, but all these objects get garbage
//collected at the end of this method, so no leak.

but how is there no loeak in noLeak method. Arent they doing the same thing which is adding to a collection.
or maybe i am missing something?

can someone point me to other real time memory leak examples
thanks
Jay
0
Comment
Question by:royjayd
  • 6
  • 5
12 Comments
 
LVL 92

Expert Comment

by:objects
ID: 34117244
theres no leak because they are adding it to a local var. So once method ends the queue (and everything in it) becomes available for gc
0
 
LVL 17

Assisted Solution

by:sweetfa2
sweetfa2 earned 200 total points
ID: 34117708
The pendingRequests collection (whilst not shown here) is allocated in the global space.  Items are being added to the queue, and are not being removed at any point, as the pendingRequest collection is always in scope during the life of the program.

As items are added to the pendingRequests collection it uses a little more space for each item allocated.  Because these items are never emptied from the queue and the pendingRequests item itself is not finished with (never goes out of scope) then it continues to leak memory.

In the noleak method, items are added to a collection that is within the scope of the method itself.  So therefore, regardless of what is added to the method, when the method finally finishes the collection will be removed via garbage collection.

Therefore, whilst the noleak method does increase memory within the method, as soon as it is finished with it is removed so memory doesn't leak.

In the leak case, the memory leaks through any cleanup at any stage.
0
 

Author Comment

by:royjayd
ID: 34137451
so let me get this straight : Here is the code snippet

static HashSet pendingRequests = new HashSet();      
...
      public void leakingRequestLog(int iter) {
            Random requestQueue = new Random();
            for (int i=0; i<iter; i++) {
                  int newRequest = requestQueue.nextInt();
                  pendingRequests.add(new Integer(newRequest));
                  // processed request, but forgot to remove it from pending requests
            }
      }


      public void noLeak(int size) {
            HashSet tmpStore = new HashSet();
            for (int i=0; i<size; ++i) {
                  String leakingUnit = new String("Object: " + i);
                  tmpStore.add(leakingUnit);
            }
            
      }

in method noLeak() just because 'tmpStore' is defined within the method, it gets garbage collected and
in method leakingRequestLog() because 'pendingRequests' is defined globally, it doesnt get garbage collected?

Am i right?

Is it because 'pendingRequests' is defined as static ? or is it because 'pendingRequests' is defined globally?
Do static variables get garbage collected?

thanks for the answers.
0
 
LVL 92

Expert Comment

by:objects
ID: 34140690
thats correct

> Is it because 'pendingRequests' is defined as static ? or is it because 'pendingRequests' is defined globally?

it is because it is still in scope

> Do static variables get garbage collected?

yes, but not until the class gets unloaded
0
 

Author Comment

by:royjayd
ID: 34141119
if i make this change like this:

      public void leakingRequestLog(int iter) {
            static HashSet pendingRequests = new HashSet();  
            Random requestQueue = new Random();
            for (int i=0; i<iter; i++) {
                  int newRequest = requestQueue.nextInt();
                  pendingRequests.add(new Integer(newRequest));                  
            }
      }

will 'pendingRequests' be garbage collected when the method ends?

thanks.
0
 
LVL 92

Expert Comment

by:objects
ID: 34141224
yes (because it goes out of scope at that point)
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:royjayd
ID: 34141290
ok but since pendingRequests is defined as  static it will not be garbage collected until the class gets unloaded?
0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 34141344
thats a different static, earlier is referring to class varibles.
static has different meaning depending on where you use it
0
 

Author Comment

by:royjayd
ID: 34141380
>>>>because it goes out of scope at that point
in the above sentence do you mean it doesnt have any references when the method ends?

thx
0
 
LVL 92

Expert Comment

by:objects
ID: 34141478
correct
0
 

Author Comment

by:royjayd
ID: 34141721
ok , if there is no static something like this

HashSet pendingRequests = new HashSet();      
...
      public void leakingRequestLog(int iter) {
            Random requestQueue = new Random();
            for (int i=0; i<iter; i++) {
                  int newRequest = requestQueue.nextInt();
                  pendingRequests.add(new Integer(newRequest));
                  // processed request, but forgot to remove it from pending requests
            }
      }

the references still remain when the method ends, correct?
0
 
LVL 92

Expert Comment

by:objects
ID: 34141764
thats correct
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now