简体   繁体   中英

Junit java.lang.OutOfMemoryError GC overhead limit exceeded

I have the following @Before method for a JUnit test:

List<MyClass> allCombinations = new ArrayList<>();

@Before
public void generateCombinations() {
    int index = 0;
    char[] binaryChars = null;
    MyClass myMockObj = mock(MyClass.class);
    for (int i = 0; i < Math.pow(2, 15); i++) {
        binaryChars = StringUtils.leftPad(Integer.toBinaryString(i), variables).toCharArray();
        when(myMockObj.method1()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method2()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method3()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method4()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method5()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method6()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method7()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method8()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method9()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method10()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method11()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method12()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method13()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method14()).thenReturn(binaryChars[index++] == '0');
        when(myMockObj.method15()).thenReturn(binaryChars[index++] == '0');
        allCombinations.add(myMockObj);
        index = 0;
    }
}

This method throws the following error:

java.lang.OutOfMemoryError: GC overhead limit exceededClose stacktrace
at java.util.Arrays.copyOf(Arrays.java:3236)

I understand from here what the error is. However, I don't know the reason in above code for getting this error.

An interesting feature of JUnit is that it creates an instance of the test class for each test case you run and those instances are not released for GC until all the tests have been run.

Thus, if you allocate a lot of data to instance variables in your test case (like in the generateCombinations method that is run before every test) you have to manually release the data after the test.

Try adding a method

@After
public void cleanup() {
    allCombinations  = null;
}

We have made a tool that makes this automatically with reflection.

If cleaning up the test classes doesn't help, then you just need to throw more memory at it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM