I was playing around with classLoaders in Java and noticed a strange thing. If a classLoader loads a class from a jar, this jar is locked indefinitely even if you unreferenc
I have found an answer and a workaround.
Based on this article and this amazing related article, it is a bad habit to use Class.forName(className, true, classLoader)
because it keeps the class cached in the memory indefinitely.
The solution was to use classLoader.loadClass(clasName)
instead, then once finished, unreference the classLoader
and call the garbage collector using:
classLoader = null;
System.gc();
Hope this helps others! :)
Background Info:
My project was a complexe one: we had a GWT server acting as a RMI client to another server. So to create instances, GWT needed to download the classes from the server and load them. Later, GWT would resend instance to the server to persist them in database using Hibernate. In order to support hot deployment, we opted for dynamically class loading where a user would upload a jar and notifies the server who would load the classes from it and present them as available to GWT server