Interview Questions

When Objects Are Garbage Collected After a Test Is Executed?

JUnit Questions and Answers


(Continued from previous question...)

When Objects Are Garbage Collected After a Test Is Executed?

My guess would be that all objects used in a test will be ready for Java garbage collector to release them immediately after the test has been executed. But it seems that I was wrong. The JUnit FAQ provided the following answer.

By design, the tree of Test instances is built in one pass, then the tests are executed in a second pass. The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run.

Therefore, if you allocate external or limited resources in a test, you are responsible for freeing those resources. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.

If this is true, the JUnit runner should be improved to stop building all test instances before executing any tests. Instead, the JUnit runner should just take one test at a time, build an instance of this test, execute the test, and release the test when the execution is done.

(Continued on next question...)

Other Interview Questions