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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With