Wednesday, October 24, 2007

Java Class Loaders

Class loaders have always been the key component of the Java, loading classes into the JVM at runtime. Class loaders fetch classes into the JVM, so they constitute the first line of defense in the JVM Sandbox, filtering malicious code, guarding trusted libraries, and setting up protection domains.

Further, the J2EE architecture makes uses of the class loaders to the fullest. Almost every component of J2EE is the dynamically loaded by the application server.

In a JVM, each and every class is loaded by some instance of a java.lang.ClassLoader. The ClassLoader class is located in the java.lang package and developers are free to subclass it to add their own functionality to class loading.



JVM creates an instance of java.lang.Class for every data type loaded into memory. The instance of this java.lang.Class is also stored on heap like any other object. Every object in Java contains a reference to this Class object of its data type. The getClass() method can be used to obtain the associated Class object. The getClass() method is inherited from the java.lang.Object hence available in every class.
Lets see an example of Dynamic class loading
public class DynamicLoader
{
public static void main(String[] args) throws Exception
{
Class toRun = Class.forName(args[0]);
String[] newArgs = scrubArgs(args);
Method mainMethod = findMain(toRun);
mainMethod.invoke(null, new Object[] { newArgs });
}
private static String[] scrubArgs(String[] args)
{
String[] toReturn = new String[args.length-1];
for (int i=1; i<args.length; i++)
{
toReturn[i-1] = args[i].toLowerCase();
}
return toReturn;
}
private static Method findMain(Class clazz) throws Exception
{
Method[] methods = clazz.getMethods();
for (int i=0; i<methods.length; i++)
{
if (methods[i].getName().equals("main"))
return methods[i];
}
return null;
}
}

public class Echo
{
public static void main (String args[])
{
for (int i=0; i<args.length; i++)
{
System.out.println("Echo arg"+i+" = "+args[i]);
}
}
}
Running DynamicLoader
>java DynamicLoader ECHO One Two Three
And the output is
Echo arg0 = One
Echo arg1 = Two
Echo arg2 = Three
As you can see, DynamicLoader created an instance of the Echo class, and called its main method, all without having any direct reference to Echo itself. In O-O parlance, this means that DynamicLoader is completely decoupled from Echo; there are no explicit dependencies between these two classes.

Class.forName(). In most of these systems, the code to do the run-time loading comes through the method forName on the class java.lang.Class; its use is demonstrated in the DynamicLoader code, above. Class.forName attempts to load the class whose name is given in its only argument, and returns the Class instance representing that class. In the event that the Class could not be found, resolved, verified, or loaded, Class.forName throws one of several different Exceptions.



CLASS LOADER


Now that we know java.lang.Class, it’s easy to comprehend the class loader of Java, which is a type of java.lang.Classloader (or its sub types).
The purpose of a class loader is to load the byte codes in ".class" file, and build the java.lang.Class object corresponding to the loaded type on JVM heap memory.


The java.lang.Class object is used to create objects requested by the programs.








Java has hierarchy of class loaders linked in a chain of parent-child relationship. Every class loader in Java, except the bootstrap class loader, has a parent class loader. At top of the parent-child chain is the bootstrap class loader.


Most java programs have at least 3 class loaders active behind the scenes. They are as follows










Bootstrap or Primordial Class loader: Class loader is responsible for loading only the core Java API (e.g. classes files from rt.jar). Since the core classes are required to bootstrap any Java program the class loader is called bootstrap class loader. This is root of all the class loader hierarchy in a java application.

Extension Class loader: Class loader responsible for loading classes from the Java extension directory (i.e. classes or jars in jre/lib/ext of the java installation directory). This class loader is responsible for loading the "installed extensions". Bootstrap class loader is the parent of this class loader.

System class loader or Application class loader: Class loader responsible for loading classes from the java class path (i.e. class directories or jars present in CLASSPATH environment variable of the Operating System). Extension class loader is the parent of this class loader. This class loader is by default the parent of all the custom/user defined class loaders in a java application.


The class loader subsystem involves many other parts of the Java virtual machine and several classes from the java.lang library. For example, user-defined class loaders are regular Java objects whose class descends from java.lang.ClassLoader. The methods of class ClassLoader allow Java applications to access the virtual machine's class loading machinery. Also, for every type a Java virtual machine loads, it creates an instance of class java.lang.Class to represent that type. Like all objects, user-defined class loaders and instances of class Class reside on the heap. Data for loaded types resides in the method area.

This use of dynamic runtime loading is the heart of Java Application Servers like the Java2 Enterprise Edition reference implementation, Enterprise JavaBeans, and the Servlet Specification. In each one of these architectures, at the time the application server is compiled, it knows nothing about the code that will be attached to it.

Instead, it simply asks the user for a classname to load, loads the class, creates an instance of the class, and starts making method calls on that instance. (It does so either through Reflection, or by requiring that clients implement a particular interface or class, like GenericServlet in the Servlet spec, or EJBObject in the EJB spec.)


The class loader subsystem is responsible for more than just locating and importing the binary data for classes. It must also verify the correctness of imported classes, allocate and initialize memory for class variables, and assist in the resolution of symbolic references. These activities are performed in a strict order:
1.Loading: finding and importing the binary data for a type
2.Linking: performing verification, preparation, and (optionally) resolution
a. Verification: ensuring the correctness of the imported type
b. Preparation: allocating memory for class variables and
initializing the memory to default values
c. Resolution: transforming symbolic references from the type into direct
references.
3.Initialization: invoking Java code that initializes class variables to their
proper starting values.



2 comments:

  1. Nice One Deepak..........Keep posting such good articles..........

    ReplyDelete
  2. Good article thank you. I tried to describe basics of class loading to.

    ReplyDelete