开发者

Java OutOfMemoryError not throwing

开发者 https://www.devze.com 2022-12-19 23:07 出处:网络
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 cre

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


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.


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


The easiest way to get an OutOfMemoryException is to create an array which doesn't fit into memory:

public class TestOutOfMemoryException
{
    public static void main(String[] args)
    {
        final long maxMemory = Runtime.getRuntime().maxMemory();
        System.out.println(maxMemory);
        final byte[] boom = new byte[(int) maxMemory];
    }
}


The variable i is only scoped to the loop, it doesn't survive past each iteration. Thus it is being garbage collected before the program can run out of memory. Try creating an ArrayList before entering the loop and adding each instance of i to it:

public class Test {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        while (true) {
            Integer i = new Integer();
            list.add(i);
        }

    }

}


try with something like a

List l = new ArrayList(); int i = 0; while(true) { l.add(i++); }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号