Class Loader Sub System

Class Loader Sub System

The class loader sub system is an essential core of the Java Virtual machine and is used for loading .class files and saving the byte code in the Java Virtual Machine (JVM) method area. Class loader sub system is responsible for loading .class file with 3 activities

  1. Loading
  2. Linking
  3. Initialization
1. Loading

Loading means read .class file from hard disk and store corresponding binary data inside method area of JVM. For each .class file JVM will store following information

  1. Fully qualified name of class
  2. Fully qualified name of immediate parent
  3. Whether .class file represents class|interface|enum
  4. Methods|Constructors|Variables information
  5. Modifiers information
  6. Constant Pool information 

After loading the class file and store inside method area, immediately JVM will perform one activity i.e., create an object of type java.lang.Class in heap area.

Created object is not student object or customer object. It is a predefined class “Class” object that is presently in java.lang package. The created object is represents either student class binary information or customer class binary information.

Here the created class “Class” object is used by programmer. For example,

package com.ashok.jvm;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {  
   private int empId;
   private String empName;
   
   public int getEmpId() {
      return empId;
   }
   public void setEmpId(int empId) {
      this.empId = empId;
   }
 
   public String getEmpName() {
      return empName;
   }
   public void setEmpName(String empName) {
      this.empName = empName;
   }
}
package com.ashok.jvm;

import java.lang.reflect.Method;
import java.lang.reflect.Field;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test {
   public static void main(String[] args) throws ClassNotFoundException {
      Class clazz = Class.forName("com.ashok.jvm.Employee");
      Method[] methods = clazz.getDeclaredMethods();
      for(Method method : methods) {
          System.out.println(method);
      }
      Field[] fields = clazz.getDeclaredFields();
      for(Field field : fields) {
          System.out.println(field);
      }
   }
}

Output

public java.lang.String com.ashok.jvm.Employee.getEmpName()
public void com.ashok.jvm.Employee.setEmpId(int)
public void com.ashok.jvm.Employee.setEmpName(java.lang.String)
public int com.ashok.jvm.Employee.getEmpId()
private int com.ashok.jvm.Employee.empId
private java.lang.String com.ashok.jvm.Employee.empName

For every loaded .class file, only one class “Class” object will be created by JVM, even though we are using that class multiple times in our program. Example,

package com.ashok.jvm;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test2 {
   public static void main(String[] args) {
      Employee employee = new Employee();
      Class clazz = employee.getClass();
      Employee employee2 = new Employee();
      Class clazz1 = employee2.getClass();
      System.out.println(clazz.hashCode());
      System.out.println(claz.hashCode());
   }
}

Output

1704856573
1704856573

Here Employee class object created two times, but class is loaded only once. In the above program even through we are using Employee class multiple times only one class Class object got created.

2. Linking

After “loading” activity JVM immediately perform Linking activity. Linking once again contain 3 activities,

  1. Verification
  2. Preparation
  3. Resolution

Java language is the secure language. Through java spreading virus, malware these kind of this won’t be there. If you execute old language executable files (.exe) then immediately we are getting alert message saying you are executing .exe file it may harmful to your system. 

But in java .class files we never getting these alert messages. What is the reason is inside JVM a special component is there i.e., Byte Code Verifier. This Byte Code Verifier is responsible to verify weather .class file is properly formatted or not, structurally correct or not, generated by valid compiler or not. If the .class file is not generated by valid compiler then Byte Code Verifier raises runtime error java.lang.VerifyError. This total process is done in verification activity. 

In preparation phase, JVM will allocate memory for class level static variables and assigned default values.

E.g. For int —> 0, For double —> 0.0, For boolean —> false

Here just default values will be assigned and original values will be assigned in initialization phase.

Next phase is Resolution. It is the process of replacing all symbolic references used in our class with original direct references from method area.

1

For the above class, class loader sub system loads Resolution.class, String.class, Student.class and Object.class. Every user defined class the parent class is Object.class so every sub class its parent class must be loaded. The names of these classes are stored in “Constant Pool” of “Resolution” class. 

In Resolution phase these names are replaced with Actual references from the method area.

3. Initialization

In Initialization activity, for class level static variables assigns original values and static blocks will be executed from top to bottom.

While Loading, Linking and Initialization if any error occurs then we will get runtime Exception saying java.lang.LinkageError. Previously we discussed about VerifyError. This is the child class of LinkageError.

Types of class loaders in class loader subsystem
  1. Bootstrap class loader/ Primordial class loader
  2. Extension class loader
  3. Application class loader/System class loader
1. Bootstrap class loader

Bootstrap class loader is responsible for to load classes from bootstrap class path. Here bootstrap class path means, usually in java application internal JVM uses rt.jar. All core java API classes like String class, StringBuilder class, StringBuffer class, java.lang packages, java.io packages etc are available in rt.jar. This rt.jar path is known as bootstrap class path and the path of rt.jar is

jdk --> jre --> lib --> rt.jar

This location by default consider as bootstrap class path. This Bootstrap class loader is responsible for loading all the classes inside this rt.jar. This Bootstrap class loader is implemented not in java it is implemented by native languages like C, C++ etc.

2. Extension class loader

The extension class loader is the child of bootstrap class loader. This class loader is responsible to load classes from extension class path

jdk --> jre --> lib-->ext -->*.jar

The extension class loader is responsible for loading all the classes present in the ext folder. This Extension class loader is implemented in java only. The class name of extension class loader is

sun.misc.Launcher$ExtClassLoader.class
3. Application class loader

The Application class loader is the child of Extension class loader. This class loader is responsible to load classes from Application class path. Application class path means classes in our application (Environment variable class path). It internally uses environment variable path. This Application class loader is implemented in java only. The class name of application class loader is

sun.misc.Launcher$AppClassLoader.class
package com.ashok.jvm;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class LoaderTest {
   public static void main(String[] args) {
       System.out.println(String.class.getClassLoader());
       System.out.println(Employee123.class.getClassLoader());
       System.out.println(LoaderTest.class.getClassLoader());
   }
}

Output

null  // Because Bootstrap class loader is not java object it is designed with C or C++
sun.misc.Launcher$ExtClassLoader@33909752 //Here i am created class Employee123 and create jar for this class and put in ext folder
sun.misc.Launcher$AppClassLoader@73d16e93
How Java Class loader works?

Class loader sub system follows delegation hierarchy algorithm. The algorithm simply looks like as following.

JVM execute java program line by line. Whenever JVM come across a particular class first JVM will check weather this .class file is already loaded or not. If it is loaded JVM uses that loaded class from method area otherwise JVM will requests class loader sub system to load the .class file then class loader sub system sends that request to application class loader. 

Application class loader won’t load that requested class, simply it delegates to extension class loader. Extension class loader also won’t load that requested class, simply it delegates to boot strap class loader. Now boot strap class loader search in boot strap class path. If the class is found in boot strap class path then loaded otherwise it delegates to extension class loader. 

Now extension class loader searches in extension class path. If the class is found in extension class path then loaded otherwise it delegates to application class loader. Application class loader now searches in application class path.

If the class is found in application class path then loaded. Suppose boot strap class loader unable find, extension class loader unable to find, application class loader unable to find then we will get run time exception called “ClassNotFound” exception. This is the algorithm that class loader sub system follows. This algorithm is called “Delegation hierarchy algorithm”.

Here the highest priority will be bootstrap class path, if the class not found in bootstrap class path the next level priority is extension class path, if the class not found in extension class path the next level priority is application class path.

Customized class loader

Sometimes we may not satisfy with default class loader mechanism then we can go for Customized class loader. For example

Default class loader loads .class file only once even though we are using multiple times that class in our program. After loading .class file if it is modified outside, then default class loader won’t load updated version of .class file on fly, because .class file already there in method area. To overcome this problem we are going to customized class loader.

4

Whenever we are using a class, customized class loader checks whether updated version is available or not. If it is available then load updated version otherwise use already loaded existing .class file, so that updated version available to our program.

public class CustomizedClassLoader extends ClassLoader {
   public Class loadClass(String cname) throws ClassNotFoundException {
       // Check whether updated version available or not. If updated version is available then 
          load updated version and returns corresponding class "Class" object. Otherwise return 
          Class object of already loaded .class
   }
}

class CustomClassLoaderTest {
   public static void main( String arg[]) {
      Student s1 = new Student(); // Default class loader loads Student.class
      .
      .
      CustomizedClassLoader c = new CustomizedClassLoader();
      c.loadClass(Student); // Customized class loader checks updates and load updated version
      .
      .
      c.loadClass(Student); // Customized class loader checks updates and load updated version
   }
}

Note

While designing/developing web servers and application servers usually we can go for customized class loaders to customized class loading mechanism.

That’s all about Class Loader Sub System in JVM. If you have any queries or feedback, please write us at [email protected]. Enjoy learning, Enjoy JVM..!!

Class Loader Sub System
Scroll to top