Saturday 19 July 2014

Create Memory leak in Java

If a program holds a reference to a heap memory that is not used during the rest of its life, it is considered a memory leak because the memory could have been freed and reused. A memory leak occurs when a computer program incorrectly manages memory allocations.

Garbage collector won't reclaim the memory due to the reference being held by the program. A Java program may run out of memory due to memory leaks.
import java.util.*;

public class ProcessRequest {
    static Vector<Integer> myVector = new Vector();
    
    static void processReq(int iter, int num){
        
        for(int j=0; j<iter; j++){
            /* Simply Adding the request */
            for(int i=0; i<num; i++){
                myVector.add(i);
            }

            /* Remove the requests */
            for(int i = num-1; i>0; i--){
                myVector.removeElementAt(i);
            }
            //System.out.println(myVector.size());
        }
    }
    public static void main(String args[]){
       while(true){
           processReq(1000, 5);
       }
    }
}

Above program simply add and removes elements from myVector. When you closely observe the program

/* Remove the requests */
for(int i = num-1; i>0; i--){
    myVector.removeElementAt(i);
}

There is a problem in the above loop. Actually we are not removing all the elements. The condition in the loop should be i>=0, but it is i>0. So for every iteration, one object is not getting removed. I.e, for Every iteration of the outer loop, one unused object is being added to heap. Even though it is unused, JVM can't help you, since, JVM de allocates memory of an object, if there is no reference count to this object.


                                                  
                                                 Home

No comments:

Post a Comment