In this Topic we will try to simulate the java.lang.OutOfMemoryError !! We will create an object holding 1MB of bytes, add it into a List, and repeat the create and add process until the JVM throw OutOfMemoryError.


    while (true) {
            // 1MB each loop, 1 x 1024 x 1024 = 1048576
            byte[] b = new byte[1048576];
            list.add(b);
    }

java.lang.OutOfMemoryError: Java heap space

This example will run a while then it will throws java.lang.OutOfMemoryError.

package com.jt;

import java.util.ArrayList;
import java.util.List;

public class JavaEatMemory {

    public static void main(String[] args) {

            List<byte[]> list = new ArrayList<>();
            int index = 1;
            while (true) {
                    // 1MB each loop, 1 x 1024 x 1024 = 1048576
                    byte[] b = new byte[1048576];
                    list.add(b);
                    Runtime rt = Runtime.getRuntime();
                    System.out.printf("[%d] free memory: %s%n", index++, rt.freeMemory());
            }

    }
}

The Output :


[2037] free memory: 7633504
[2038] free memory: 5536352
[2039] free memory: 3439104
[2040] free memory: 1573072
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.mkyong.JavaEatMemory.main(JavaEatMemory.java:20)

Source : Mkyong

Tagged: