Sree Sake
Sree Sake

Reputation: 83

Recovering from Out of Memory Exception within the JVM and reset JVM if possible

I am creating a test suite to run functional tests for an application that my team is developing. The functional tests are written by individual developers, and I observed that some testcases are throwing a OutOfMemoryError due to various reasons. This keeps happening intermittently.

To handle this situation I want to catch OutOfMemoryError in my test suite. I am hoping that catching this error would allow me to run subsequent testcases without having to quit the application all together. But I came across a post saying Out Of Memory Error is thrown after garbage collection is complete. In that case, Can I do something in my catch block of OutOfMemoryError to cleanup/re-instate JVM and then continue the execution?


    Map<String, String> testcaseStatuses = new HashMap<String, String>();
    String testcaseStatus = "FAIL";
    for(Testcase testcase : testcases)
    {
        try
        {
            runTestcase(testcase);
            testcaseStatus = "SUCCESS";
        }
        catch(OutOfMemoryError e)
        {
            logError(e);
            testcaseStatus = "SYSTEM_ERROR";
                        // Do something creative to re-initialize JVM
        }
        catch (Exception e)
        {
            logError("Testcase failed with exception : " + e);
        }
        finally
        {
            testcaseStatuses.put(testcase.getName(), testcaseStatus);
        }
    }

    // Do something with testcaseStatuses   

I wouldn't want to stop running the remaining testcases if the first one fails. Is this something feasible?

NOTE: I did come across several posts here on SO, on using

-XX:OnOutOfMemoryError="New script to run"

This is something I am considering for the moment. But in order to follow this path, I would have to re-design the entire way I am executing the testcases which I want to avoid If I can.

Thanks in advance.

Upvotes: 1

Views: 160

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

Impossible from within the JVM that ran out of memory.

Of course in theory you should fix the cause(s) of those OutOfMemoryErrors, or make sure that those who are responsible fix them. However given the real life scenario that you are in, I'd suggest redesigning your test application to encapsulate each test in its own JVM, e.g. like so:

  • Create one application that can execute the tests, but only ever one at a time, chosen by a runtime argument.

  • Create an application that runs the former application in a separate process, once for each test. Then use console output, logging data and/or the process return value to determine the state of the test, including if it ran out of memory.

Upvotes: 1

Related Questions