Tuesday, April 10, 2007

Java ClassLoaders

Class loader delegation model is the graph of class loaders that pass loading requests to each other. The bootstrap class loader is at the root of this graph. Class loaders are created with a single delegation parent and looks for a class in the following places:
  • Cache
  • Parent
  • Self
Three standard class loaders:
  • bootstrap class loader (jre/lib)
  • extension class loader (jre/lib/ext)
  • system class loader (CLASSPATH)
Three phases of class loading
  • loading: locating the required class file
by searching through the respective classpaths and loading in the bytecode. Within the JVM, the loading process gives a very basic memory structure to the class object. Methods, fields, and other referenced classes are not dealt with at this stage. As a result, the class is not usable.

  • Linking is the most complicated of the three phases. It can be broken down into three main stages:
  • Bytecode verification. The class loader does a number of checks on the bytecodes of the class to ensure that it is well formed and well behaved.
  • Class preparation. This stage prepares the necessary data structures that represent fields, methods, and implemented interfaces that are defined within each class.
  • Resolving. In this stage, the class loader loads all the other classes referenced by a particular class. The classes can be referenced in a number of ways:
    - Superclasses
    - Interfaces
    - Fields
    - Method signatures
    - Local variables used in methods
  • initializing phase
Any static initializers contained within a class are executed. At the end of this phase, static fields are initialized to their default values.

At the end of these three phases, a class is fully loaded and is ready for use. Note that class loading can be performed in a lazy manner and therefore some parts of the class loading process may be done on first use of the class rather than at load time.

Explicit and Implicit loading

Explicit:
cl.loadClass() (cl instance of java.lang.ClassLoader)
Class.forName()

Articles
Part 1
Part 2
Part 3
Part 4

No comments: