Translate

Saturday, October 15, 2011

Class Loading

Basic
  • Class loaders are responsible for loading classes into the Java Virtual Machine (JVM). 
  • There are two important concepts around Class Loader paradigm. Isolation & Delegation. 
  • Isolation guarantees that class loaded by class loader 1 is not equal to the same class loaded by class loader 2. Also a parent class loader is unable to "see" a class loaded by child class loader. 
  • A class loader verifies the class cache to return an already loaded one. If it does not find one, as par delegation model it first asks its parent to load a class before it starts to load the class on its own
  • Bootstrap class loader is primordial one that loads core system classes from the boot class path
  • This is extended by extension classloader that loads classes from jre/lib/ext directory
  • This is extended by System class loader that loads classes found on the CLASSPATH environmenal variable. This is also the class loader returned by the ClassLoader.getSystemClassLoader() method.Any custom class loaders are expected to extend System class loader

Loading step by step
  • Class Loading is a step by step process. There are three stages for a class loading to happen. These are loading, linking and initializing.
  • During loading raw bytes are located and read into JVM. Basic memory structure is assigned to the attributes, methods and other referenced classed
  • During linking three smaller tasks happens sequentially, first bytecode is verified to ascertain that it is a valid bytecode, then at the "class preparation" stage appropriate data structure for the fields, method and implemented interfaces are defined, finally at "resolving" stage all other classes that are referenced by the field, interface, superclass, method signature and local variable are loaded.
  • During initialization all static variables are initialized to default value and static blocks are executed
  • Implicit vs Explicit loading
  • Explicit loading is loading a class via Class.forName or classLoader.loadClass method
  • Implicit loading is loading of a class on being referenced as discovered during the resolving sub task of  linking phase as mentioned earlier
Class Loading - Exception
  • ClassNotFoundException is the most common type of class loading exception. It occurs during the loading phase. The Java specification describes ClassNotFoundException as follows:
Thrown when an application tries to load in a class through its string name using:
o    The forName() method in class Class.
o    The findSystemClass method() in class ClassLoader.
o    The loadClass() method in class ClassLoader.
but no definition for the class with the specified name could be found.
By throwing a ClassNotFoundException, the class loader informs you that the bytecode required to define the class is simply not present in the locations where the class loader is looking for it.
  • NoClassDefFoundError is thrown when a class is not found during implicit classloading. This happens when a class was present during the compilation of the target class but now unavailable when the target class is getting loaded at run time. This missing class can be required as an argument to the method call or used with the new operator.
  • ClassCastException is when code tries to cast an object to a sub class of which it is not an instance of
  • UnstatisfiedLinkError is being thrown when a native library is not found while loading
  • ClassCirculatoryError is being thrown when there exists a circulatory class hierarchy. This usually happen in complex systems during resolving stage
  •  ClassFormatError happens during verification sub stage of linking phase when the binary data that represents the class is found to be malformed
  • Problems faced during class loading
    • Classpath related : if following two paths are supplied to the URLClassLoader namely /a/b/c & /a/b/c/ then the class loader assumes that the first path refers to a jar and the second path refers to a directory
    • Class visibility: A class loader can only see classes to which it has direct or indirect reference. In delegation model it turns out that the class loader in question will be able to see what its parent has loaded but not its child
    • Overriding loadClass() : in case it requires manually invoking loadClass method following code should be written by the custom classloader
public Class loadClass(String name) throws ClassNotFoundException {
    Class c = null;
    try {
        c = getParent().loadClass(name);
    } catch (ClassNotFoundException e) {
    }
    if(c == null)
        c = findClass(name);
    return c;
}
Instead of using getParent.loadClass() have had we been invoking loadClass directly exception would have been thrown as parent class loaders are never invoked and therefore system classes are not being loaded
However this implementation has a drawback as loadClass always tries to load a class instead of verifying if that exists in the cache. This is why the method should be modified such that instead of initializing variable c to null, findLoadedClass method is invoked which first verifies the cache to return an already loaded instance
    • Garbage collectors monitor the lookup tables associated with the classloader to figure out which class can be garbage collected. However if a classloader itself is garbage collected, that classed it loaded are lost as well