简体   繁体   English

为什么无限对象创建不会抛出OutOfMemoryError?

[英]Why is infinite object creation not throwing OutOfMemoryError?

Why am I not getting OutOfMemoryError with the below code? 为什么我没有使用以下代码获取OutOfMemoryError?

class OutOfMemoryErrorTest{

    public static void main(String[] args){
        Object obj;

        while(true){
            obj = new Object();
        }
    }
}

I am running with Java 8. 我正在运行Java 8。

The obj will be marked collectable after each loop, so it will be collected. 每次循环后,obj将被标记为可收集,因此将被收集。

    while(true){
        Object obj = new Object(); //no further reference, so obj will be collected
    }

If you need to test OOM, you should save the reference of obj to a LinkedList. 如果需要测试OOM,则应将obj的引用保存到LinkedList。

    List refs = new LinkedList();
    while (true) {
        Object obj = new Object();
        refs.add(obj);
    }

Then you will get the OOM as you wanted. 然后你会得到你想要的OOM。 And you can use a smaller heap to reach OOM sooner. 并且您可以使用较小的堆来更快地到达OOM。

Because you did not save the object reference, so garbage collector remove the created objects. 因为您没有保存对象引用,所以垃圾收集器删除创建的对象。 if you add these objects to List then it will happened. 如果你将这些对象添加到List,那么它将会发生。

So firstly it simply gets removed by the garbage collector cause you create it in a loop. 首先,它只是被垃圾收集器删除,因为你在循环中创建它。 Secondly it could be you have so much memory that you just have to wait long. 其次,你可能有很多记忆,你只需要等待很长时间。 So when u fixed the garbage collector thing you may wait long. 因此,当你修复垃圾收集器时,你可能需要等待很长时间。 Try this code i found on https://crunchify.com/how-to-generate-out-of-memory-oom-in-java-programatically/ 试试我在https://crunchify.com/how-to-generate-out-of-memory-oom-in-java-programatically/上找到的代码

package test;

public class OutOfMemoryErrorTest {

    /**
     * @author Crunchify.com
     * @throws Exception
     * 
     */

    public static void main(String[] args) throws Exception {
        OutOfMemoryErrorTest memoryTest = new OutOfMemoryErrorTest();
        memoryTest.generateOOM();
    }

    public void generateOOM() throws Exception {
        int iteratorValue = 20;
        System.out.println("\n=================> OOM test started..\n");
        for (int outerIterator = 1; outerIterator < 20; outerIterator++) {
            System.out.println("Iteration " + outerIterator + " Free Mem: " + Runtime.getRuntime().freeMemory());
            int loop1 = 2;
            int[] memoryFillIntVar = new int[iteratorValue];
            // feel memoryFillIntVar array in loop..
            do {
                memoryFillIntVar[loop1] = 0;
                loop1--;
            } while (loop1 > 0);
            iteratorValue = iteratorValue * 5;
            System.out.println("\nRequired Memory for next loop: " + iteratorValue);
            Thread.sleep(1000);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM