I get this error message as I execute my JUnit tests:
java.lang.OutOfMemoryError: GC overhead limit exceeded
I know what an OutOfMemo
It's usually the code. Here's a simple example:
import java.util.*;
public class GarbageCollector {
public static void main(String... args) {
System.out.printf("Testing...%n");
List list = new ArrayList();
for (int outer = 0; outer < 10000; outer++) {
// list = new ArrayList(10000); // BAD
// list = new ArrayList(); // WORSE
list.clear(); // BETTER
for (int inner = 0; inner < 10000; inner++) {
list.add(Math.random());
}
if (outer % 1000 == 0) {
System.out.printf("Outer loop at %d%n", outer);
}
}
System.out.printf("Done.%n");
}
}
Using Java 1.6.0_24-b07 on a Windows 7 32 bit.
java -Xloggc:gc.log GarbageCollector
Then look at gc.log
Now granted, this is not the best test or the best design but when faced with a situation where you have no choice but implementing such a loop or when dealing with existing code that behaves badly, choosing to reuse objects instead of creating new ones can reduce the number of times the garbage collector gets in the way...