Closing a URLClassLoader

Complex Java programs such as application servers sometimes create their own class loaders using the URLClassLoader type. With URLClassLoader, applications can load classes and resources from a search path of URLs, and the following URL types are supported:
  • file:
  • jar:
  • http:
which load from file-system directories, jar files, and http servers respectively.

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.

The new method follows the familiar "Closeable" pattern, and URLClassLoader now implements that interface. The definition of URLClassLoader.close() can be seen here.

Comments:

For the last 5 years or more I've been having problems with Tomcat throwing OutOfMemoryErrors for PermGen space. I wonder if that will fix that problem? If it does, I will be AMAZED!

Posted by Jon on June 03, 2009 at 06:18 AM PDT #

Hi Michael,

It's a great Idea, but did you think would be necessary to implement a "boolean isClosed()" method too?... following some APIs that used to do it !

Keep Going !!!

Posted by Omar Granados on August 11, 2009 at 05:02 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

michaelmcmahon

Search

Top Tags
Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today