Saturday, September 17, 2005

Garbage Collection

public class Runner {

public static void main(String[] args) {

MyType myType = new MyType();

myType=null; // Line 1

java.util.ArrayList arrayList = new java.util.ArrayList(); //line 5

while(true) {

arrayList.add(new String("waste"));

}

}

}


class MyType{

protected void finalize() {

System.out.println("bye");

}

}

output:

bye

Exception in thread "main" java.lang.OutOfMemoryError


Why this program is printing bye?

Why this program is printing bye followed by OutOfMemoryError?

java.lang.OutOfMemoryError:

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

This Program demonstrates how JVM runs Garbage Collecter atleast once before giving error(OutOfMemoryError). Garbage Collector calls "finalize()" method before trying to delete Objects. Since no Objects can be deleted we get runtime error.

This program also demostrates how a strong reference stops an Object from being Garbage Collected.

Example "Line 1" if it is commented then that means there is a strong reference to MyType instance meaning it cannot be garbage collected. You will not see "bye" in the output.

output:

Exception in thread "main" java.lang.OutOfMemoryError

1 Comments:

Anonymous Anonymous said...

after adding a SOP in while loop memory error doesn't come...
S T R A N G E ....
while(true)
{System.out.println(++i);
arrayList.add(new String("waste"));
}

Tuesday, October 18, 2005 4:50:00 pm  

Post a Comment

<< Home