Donald Donald -4 years ago 124
Java Question

Java out of memory errors

Why does this following code

List<Object> list = new ArrayList<>();
while (true) {
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}


produce an out of memory error

But this code doesn't

while(true) {
List<Object> list = new ArrayList<>();
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}


I can see that it has something to do with the list being created either inside the while loop or outside of it obviously, but I am unsure on the reason why this happens.

Answer Source

In the first case, you have a single ArrayList instance and you keep adding to it new Object instances until you run out of memory.

In the second case, you create a new ArrayList in each iteration of the while loop and add 1000000 Object instances to it, which means the ArrayList created in the previous iteration and the 1000000 Object instances it contains can be garbage collected, since the program no longer has references to them.

Note that the second snippet can also cause out of memory error if the new Objects are created faster than the garbage collector can release the old ones, but that depends on the JVM implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download