Friday, January 22, 2010

Java Class Loading

Article from internet

In Java, a class is identified by its fully qualified class name. The fully qualified class name consists of the package name and the class name. But a class is uniquely identified in a JVM using its fully qualified class name along with the instance of theClassLoader that loaded the class. Thus, if a class named Cl in the package Pg is loaded by an instance kl1 of the class loaderKlassLoader, the class instance of C1, i.e. C1.class is keyed in the JVM as (Cl, Pg, kl1). This means that the two class loader instances (Cl, Pg, kl1) and (Cl, Pg, kl2) are not one and the same, and classes loaded by them are also completely different and not type-compatible to each other.


  • bootstrap class loader
  • ExtClassLoader is responsible for loading all .jar files kept in the java.ext.dirs path.
  • AppClassLoader is responsible for loading all of the classes kept in the path corresponding to the java.class.path system property
  • customized class loaders…


One of the reasons for a developer to write his or her own class loader is to control the JVM's class loading behavior.

But let us think of a scenario where we need to develop a generic Execution Engine, capable of executing any tasks implementing a particular interface. When the tasks are submitted to the engine, first the engine needs to load the code for the task. Suppose different clients submit different tasks (i.e., different code) to the engine, and by chance, all of these tasks have the same class name and package name. The question is whether the engine will load the different client versions of the task differently for different client invocation contexts so that the clients will get the output they expect.


Since there is no explicit class versioning mechanism, if we want to load classes (same name, same package) at our own will, we have to use custom class loaders with extended capabilities. Many J2EE application servers have a "hot deployment" capability, where we can reload an application with a new version of class definition, without bringing the server VM down. Such application servers make use of custom class loaders. Even if we don't use an application server, we can create and use custom class loaders to finely control class loading mechanisms in our Java applications.

No comments:

Post a Comment