Search code examples
javaclassloader

How to unload Java standard libraries


Is it possible to unload Java standard libraries - those defined in the java.* packages?

My application needs to run JUnit tests, each with its own ClassLoader, like so:

for(String testClass : testClasses) {
    CustomClassLoader cl = new CustomClassLoader(this.getClass().getClassLoader());
    Class<?> _class = cl.loadClass(testClass);
    JUnitCore junit = new JUnitCore();
    Result result = junit.run( _class );
    registerResult(result, cl);
}

The problem that I am having is that some classes are not unloaded - the java.* classes.

If I do not unload them, then what happens is if the testing classes store objects using static methods, like those provided by the java.security.Security class, then I get a ClassCastException.

Is there any way for me to force their unloading?


Solution

  • It is not possible to force unloading of classes. As long as a class or an instance of the class is referenced it wont be collected by the gc. You will have to remove these global values manually before or after each test.

    For unit tests you can try to run every test in a fresh jvm. (this will avoid static class data but wont avoid other global remains like files).

    These links may help:

    Running each JUnit test in a separate JVM in Eclipse?

    How to tell Maven2 to execute jUnit tests one by one each in new JVM instance?