How to simulate java.lang.OutOfMemoryError in Java

The idea is simple, 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);
	}

1. java.lang.OutOfMemoryError: Java heap space

Below Java example will run a while and throws java.lang.OutOfMemoryError.

JavaEatMemory.java

package com.mkyong;

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());
			}

	}
}

Output

Terminal

[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)

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments