Solved

memory leak example

Posted on 2010-11-11
12
618 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

759 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