Thursday, 23 June 2011

Class Loaders - simplified - part 1

As discussed in my previous post, class loaders is one of the components of JVM. It is responsible for finding and loading the class at run time.

Classes are loaded into the JVM as they are referenced by name in a class that is already running in JVM. The first class is loaded into memory by invoking the static void main method of the class. All subsequent classes are loaded by classes which are previously loaded and running.

The following class loaders are created by the JVM
  1. Bootstrap or primordial class loader: Is the default class loader which is associated with the JVM. You can hook your own custom class loader instead of the default. All the JDK internal classes java.* packages i.e the ones that belong to rt.jar or i18n.jar are loaded by this class loader. (as defined in the sun.boot.class.path system property)
  2. Extension class loader: loads classes that are part of the extensions directory typically the lib/ext directory of the JRE are loaded by this class loader. (as defined in the java.ext.dirs system property)
  3. System class loader: loads classes that are part of the system class path (as defined by the java.class.path system property which is set by the CLASSPATH environment property, or -classpath / -cp command line options)
Classes loaded by different class loaders are placed into separate name spaces inside the Java virtual machine.
Class Loaders not just loads but performs the following activities in sequence.
  1. Loading - finding and importing the binary data of the type in the .class file.
  2. Linking - involves verification, preparation and resolution.
    • Verification - involves ensurinNumbered Listg that the binary data is structurally valid, else will throw VerifyError.
    • Preparation - involves allocating memory for class variables and initializing the memory to the default values.
    • Resolution - is the process of transforming the symbolic references from the type into direct references.
  3. Initialization - invokes code that initializes class variables to their proper starting values.
Class loaders use delegation model to load classes. Whenever a class requires to be loaded, the class loaders will contact its parents to load the class before they themselves try. Once the class loaders loads the class, the child class loader in the hierarchy will never reload the class. Classes loaded by the child class loaders have visibility into the classes loaded by parent class loaders but the reverse is not true. If there are sibling class loaders, then the sibling class loaders do not see the classes loaded by each other.


More on class loaders in my next blog. I will cover scenarios when you would encounter NoClassDefFoundError and ClassNotFoundException.


No comments:

Post a Comment