By michaelmcmahon on Mar 03, 2009
A frequent problem has been how to support updated implementations of the classes and resources loaded from a particular codebase, and in particular from jar files. In principle, once the application clears all references to a loader object, the garbage collector and finalization mechanisms will eventually ensure that all resources (such as the JarFile objects) are released and closed. The application can then replace the jar file, and create a new URLClassLoader instance to load from the same location, but this time using the new implementation of the classes/resources. However, since it can't be predicted exactly when finalization and garbage collection will occur, this causes problems for applications which need to be able to do this in a predictable and timely fashion. It is a particular problem on Windows, because open files cannot be deleted or replaced.
To alleviate this problem, URLClassLoader has acquired a new method called close() (since b48 of jdk7) which effectively invalidates the loader, so that no new classes can be loaded from it. It also closes any jar files that were opened by the loader. This allows the application to delete/replace these files and if necessary create new loaders using new implementations.