The java.lang.OutOfMemoryError: GC overhead limit exceeded error
is an error thrown by the Java virtual machine to indicate that the application is spending more time in garbage collection (GC) than in useful work. This error is thrown by JVM when the application spends 98% of the time in garbage collection.
In the code below, a map is created and random values are inserted in an infinite loop.
Remember: In maps, heap memory is used.
import java.util.*;
class Main {
public static void main(String args[]) throws Exception {
Map map = System.getProperties();
Random rnd = new Random();
while (true) {
map.put(rnd.nextInt(), "val");
}
}
}
When we try to execute this code, using a parallel garbage collector,the GC overhead limit exceeded error
is thrown.
java -Xmx100m -XX:+UseParallelGC Main.java
Remember: The above command is executed on the command-line terminal when you are in the file containing
Main.java
.
The trick is to prevent memory leaks in your program; being careful about the following factors can help you avoid this error:
Identify the objects in your application that occupy a large space on the heap.
Identify the places in your application where memory-allocation on the heap is done.
Avoid creating a large amount of temporary or weakly-referenced objects since they increase the chances of memory leakage.
Free Resources