Recreate OutOfMemoryError in Java

[1500 views]



To recreate OutOfMemoryError, what we will be doing is adding huge amount of data(8MB byte Object) in a list, until compiler throws the error.

while (true) { byte[] b = new byte[67108864]; // 8MB Data in each iteration list.add(b); ... }

Full Java Code:

import java.util.ArrayList; import java.util.List; public class OutOfMemoryRecreate { public static void main(String[] args) { List<byte[]> list = new ArrayList<>(); int index = 1; while (true) { byte[] b = new byte[67108864]; // 8MB Data in each iteration list.add(b); Runtime rt = Runtime.getRuntime(); System.out.printf("[%d] free memory: %s%n", index++, rt.freeMemory()); } } }

Output:

C:\Users\qwerty\Desktop>javac OutOfMemoryRecreate.java C:\Users\qwerty\Desktop>java OutOfMemoryRecreate [1] free memory: 64962768 [2] free memory: 64843584 [3] free memory: 64925840 [4] free memory: 64998664 [5] free memory: 64768232 [6] free memory: 64768232 [7] free memory: 64878480 [8] free memory: 64878480 [9] free memory: 64812616 [10] free memory: 64812616 [11] free memory: 64820720 [12] free memory: 64820720 [13] free memory: 64796672 [14] free memory: 64796672 [15] free memory: 64805040 [16] free memory: 64280752 [17] free memory: 64816272 [18] free memory: 64816272 [19] free memory: 64785424 [20] free memory: 64785424 [21] free memory: 64815912 [22] free memory: 64815912 [23] free memory: 64800920 [24] free memory: 64800920 [25] free memory: 64828408 [26] free memory: 64828408 [27] free memory: 64784800 [28] free memory: 64784800 [29] free memory: 64784800 [30] free memory: 64822056 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemoryRecreate.main(OutOfMemoryRecreate.java:11)
                 




Comments



Search

For any inquiry, Contact us at atechdailyweb@gmail.com




Facing Programming Errors. Get Answers within 24 hours:


Recommendation Based on your Interest




Quiz For You:
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    What is OutOfMemory Error in java