Closing a URLClassLoader

How to Close a URLClassLoader?

The URLClassLoader close() method effectively eliminates the problem of 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, problems are caused for applications which need to be able to do this in a predictable and timely fashion. It is a problem on Windows, because open files cannot be deleted or replaced.

In Java SE 7, the URLClassLoader close() method 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 or replace these files and, if necessary, create new loaders using new implementations.

The close() method follows the familiar "Closeable" pattern, and URLClassLoader now implements the Closeable interface, which defines URLClassLoader.close(). The following sample code shows how one might use the method.

       //
       // create a class loader loading from "foo.jar"
       //
       URL url = new URL("file:foo.jar");
       URLClassLoader loader = new URLClassLoader (new URL[] {url});
       Class cl = Class.forName ("Foo", true, loader);
       Runnable foo = (Runnable) cl.newInstance();
       foo.run();
       loader.close ();

       // foo.jar gets updated somehow

       loader = new URLClassLoader (new URL[] {url});
       cl = Class.forName ("Foo", true, loader);
       foo = (Runnable) cl.newInstance();
       // run the new implementation of Foo
       foo.run();


Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.