Before you begin, you must complete Exercise 1.3: Analyzing leak candidates.
Now you know that the secondary queue is the leaking queue. Let's look at the source code to find the problem.
To open the source for the secondary queue and fix the memory leak:
public class SecondaryQueue { private Vector myQ; private int currentPos; public SecondaryQueue(){ myQ = new Vector(); currentPos=0; } public void add(Object obj){ myQ.add(obj); } public Object getNext(){ // First In First Out. // Get an object exactly once, // currentPos keeps track of last item removed. if(myQ.size()>currentPos){ currentPos++; return myQ.get(currentPos-1); } } }
public class SecondaryQueue { private Vector myQ; private int currentPos; public SecondaryQueue(){ myQ = new Vector(); currentPos=0; } public void add(Object obj){ myQ.add(obj); } public Object getNext(){ if(myQ.size()>0){ return myQ.remove(0); } return null; } }
From the main menu, click File > Save to save your changes.
Now profile the application again, capturing heap dumps just as before. When you analyze for leaks, the Leak Candidates view tells you that "Leak Analysis did not result in any leak candidates." You've fixed the leak in the secondary queue, and the Leak Candidates algorithm has not found any additional leaks.
Finish this tutorial by reviewing the materials in the Summary.