Error java.lang.OutOfMemoryError: GC overhead limit exceeded

后端 未结 20 2337
攒了一身酷
攒了一身酷 2020-11-21 05:23

I get this error message as I execute my JUnit tests:

java.lang.OutOfMemoryError: GC overhead limit exceeded

I know what an OutOfMemo

20条回答
  •  误落风尘
    2020-11-21 05:32

    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

    • Triggered 444 times using BAD method
    • Triggered 666 times using WORSE method
    • Triggered 354 times using BETTER method

    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...

提交回复
热议问题