# Exercise 1.4: Fixing the memory leak

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:

1. Select Window > Open Perspective > Java.
2. In the Package Explorer, expand the entry for `ThreeTierQueue`, and then the entry for `com.queues`.
3. Double-click the entry for `SecondaryQueue.java`. The Java Editor view opens, and displays the following code:

       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);
       		}
       	}
       }

4. Keeping in mind that you are looking for a `Vector` object that is holding on to references to many `String` objects, consider the method `Object getNext()`.
   In Java, vectors are commonly arrays of objects. An array of this kind, when it fills up, can expand to accommodate additional objects. The only limit is the amount of memory available. It is possible to add objects to an array until the array uses so much memory that your application crashes.
   Fortunately, you can also remove objects from vectors. Our code has been adding string objects to the vector, but has been neglecting to remove them.
5. Copy the corrected version given below and paste it into your source in the Java Editor view, replacing the problematic code. This version keeps the vector size within limits by removing a string when it is no longer needed.

       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;
       	}
       }

### Verifying your results

From the main menu, select 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.

Terms of use | Feedback
(C) Copyright IBM Corporation 2000, 2005. All Rights Reserved.