Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OutOfMemoryError not throwing

I was trying to study different exceptions in Java and came across the OutOfMemoryError and I wanted to see it in work so I wrote the following program to create infinite objects by creating them in a infinite loop. The program does go in infinite loop it does not throw the OutOfMemoryError exception.

class Test {
    public static void main(String...args) {
        while(true) {
            Integer i = new Integer();
        }
    }
}
like image 360
TopCoder Avatar asked Feb 14 '10 14:02

TopCoder


2 Answers

You are on the right track. The only thing you are missing is the concept of garbage collection. The program does infact create infinite Integer objects but after the 1st iteration, the object created in the previous iteration becomes eligible for GC.

Consider this:

Integer i;    
i = new Integer(); // 1. create new object and make reference variable i refer to it.
i = new Integer(); // 2. create another object and make reference variable i refer to it...there is no way to get to the object created in step1 so obj in step 1 is eligible for GC.

If you want to see the OutOfMemoryError you need to somhow make sure that there is a way to get to the objects created in the infinite loop. So you can do something like:

class Test {
 public static void main(String...args) {
  Vector v = new Vector(); // create a new vector.
  while(true) {
   v.addElement(new Integer(1)); // create a new Integer and add it to vector.
  }
 }
}

In this program Integer objects are created infinitely as before but now I add them to a vector so ensure that there is a way to get to them and they do not become GC eligible.

like image 172
codaddict Avatar answered Oct 06 '22 19:10

codaddict


Your variable i is garbage collected before you hit the OutOfMemoryError, since it isn't used anymore.

like image 28
Maurits Rijk Avatar answered Oct 06 '22 20:10

Maurits Rijk