简体   繁体   中英

Why is infinite object creation not throwing OutOfMemoryError?

Why am I not getting OutOfMemoryError with the below code?

class OutOfMemoryErrorTest{

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

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

I am running with Java 8.

The obj will be marked collectable after each loop, so it will be collected.

    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.

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

Then you will get the OOM as you wanted. And you can use a smaller heap to reach OOM sooner.

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.

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/

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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