Java JVM Memory Eater
This is a simple Java program that runs until all available JVM memory is used before ending with an exception.
package jvmmemoryeater;
import java.util.ArrayList;
public class JvmMemoryEater {
static int divby = 1048576;
public static void main(String[] args) {
System.out.println(
"Iteration, maxMemory MB, totalMemory MB, freeMemory MB"
);
int iInterval = 0;
ArrayList<byte[]> a = new ArrayList<byte[]>();
while (true) {
if (iInterval == 1000) {
report(a.size());
iInterval = 0;
}
byte b[] = new byte[1024];
a.add(b);
iInterval++;
}
}
private static void report(int i) {
Runtime r = Runtime.getRuntime();
long mm = r.maxMemory() / divby;
long tm = r.totalMemory() / divby;
long fm = r.freeMemory() / divby;
System.out.println(
"" + i + ", " + mm + ", " + tm + ", " + fm
);
}
}
When run at the command line it outputs
before finally ending with the exception
java -Xms100M -Xmx200M -jar jvmMemoryEater.jar
Iteration, maxMemory MB, totalMemory MB, freeMemory MB
1000, 177, 95, 94
2000, 177, 95, 93
3000, 177, 95, 92
4000, 177, 95, 91
5000, 177, 95, 90
6000, 177, 95, 89
If the CSV output is viewed as a graph it appears as:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at jvmmemoryeater.JvmMemoryEater.main(JvmMemoryEater.java:23)