Reputation: 87
Below program (prog1) throws OutOfMemoryError error. Rightly so. But if I add sysout below line 5(prog2), it wont throw error. Any reason for this strange behaviour?
prog1:
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
try {
while (true) {
myList.add("My String"); //5
}
} catch (Exception e) {
e.printStackTrace();
}
}
prog2:
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
try {
while (true) {
myList.add("My String");
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 1
Views: 50
Reputation: 719239
The second version will also run out of memory eventually. (If you don't get bored and kill it first.)
The problem is that the print statement is repeatedly printing a list that is getting longer and longer.
By the time you have added N items to the list in the second version, you will have printed lists of sizes 1 + 2 + 3 + ... + N
. That is N * (N + 1) / 2
copies of the string "My String"
... and some more. That is O(N^2)
.
If you are writing that to a /dev/null
it will take a long time. If you write it to a file, longer. If you write it to a console displaying on your screen ... come back in a few hours.
As an experiment, replace
System.out.println(myList);
with
System.out.print("X");
Now you will only print O(N)
characters instead of O(N^2)
... and the OOME will happen a lot sooner.
Upvotes: 2