java.lang.OutOfMemoryError: Java heap space
over this Memorial Day weekend. That's quite a coincidence. Actually, it can happen on any day, especially at night from my experience.It's also a popular Java job interview question: why are there memory leaks in Java programs? Isn't Java supposed to automatically manage memory and garbage collection? How do you debug and solve it? Number one cause of memory leak is these dying objects are still referenced by other long-living objects. This is a simple program to reproduce
java.lang.OutOfMemoryError
:package com.javahowto.test;Running with default JVM options (heap size 64m),
import java.util.Map;
import java.util.HashMap;
public class MemoryHog {
public static final Map threadMap = new HashMap();
public static void main(String[] args) {
MemoryHog hog = new MemoryHog();
for(int i = 0; ; i++) {
hog.work(String.valueOf(i));
}
}
private void work(String id) {
Thread thread = new Thread(){
public void run() {
//@TODO: do some work
}
};
System.out.println("Current thread map size: " + threadMap.size());
threadMap.put(id, thread);
thread.start();
}
}
MemoryHog
crashes when the pool size reaches 296,733. Various solutions are available:- Application designers will get rid of the pooling, or implement it correctly such that it reuses threads and set pool's initial size, max size, incremental size, and eviction policy.
MemoryHog
runs happily ever after. - Coders will just change the
HashMap
tojava.util.WeakHashMap
, andMemoryHog
runs happily ever after. - Hackers will bump up heap size, with JVM option
-Xmx128m
.MemoryHog
runs happily until the pool size grows to 592,646. Then keep doubling the heap size to makeMemoryHog
happy.