• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Exception in thread “main” java.lang.OutOfMemoryError: GC overhead limit exc

case

  • The JVM parameter test was intended to test for an exception where the constant pool in the method area ran out of memory. But the above error was thrown.
  • First, the parameters are set as follows
​
-verbose:gc
-Xms20M
-Xmx20M
-Xmn10M
-XX:MetaspaceSize=5M
-XX:MaxMetaspaceSize=10M
-XX:+PrintGCDetails
-XX:SurvivorRatio=8
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=D:\jvm
-XX:+PrintFlagsFinal
​
Copy the code
  • -xx :MetaspaceSize=5M and -xx :MaxMetaspaceSize=10M indicate the memory size limit of the method area.
Public class RuntimeConstantError {public static void main(String[] args) {//List keeps references to the constant pool. List<String> List = new ArrayList<>(); int i =0 ; while (true) { list.add(String.valueOf(i++).intern()); }}}Copy the code
  • Keep adding variables to the constant pool using the String. Intern method as described above. And always keep references to prevent GC. Eventually there will be a package memory overflow error. But it didn’t.

why

New error type in JDK6.

This exception is thrown when GC is spending a lot of time freeing very little space (Sun's official definition: more than 98% of the time GC is doing and less than 2% of the heap is reclaimed). Usually because the heap is too small, the cause of the exception: there is not enough memory.Copy the code

Ii. Solutions:

1. See if the system has code that uses large amounts of memory or an infinite loop. 2. You can add JVM startup parameters to limit memory usage: -xx: -usegCoverheadLimitCopy the code

Case analysis

  • By looking at the log, we can see that we are always thinking about adding variables to the constant area. We GC when we run out of memory, but we keep referencing. So the GC does not collect garbage. The number of GC is small, so the limited error will be reported. When we add UseGCOverheadLimit, we get an out-of-memory error classic error.Exception in thread "main" java.lang.OutOfMemoryError: Java heap space