Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 540
JavaUser Avatar asked Apr 01 '26 08:04

JavaUser


1 Answers

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.

like image 107
sanigo Avatar answered Apr 02 '26 20:04

sanigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!