Aug 5, 2017

Understanding JVM: Class Loader Sub System - Part 2

First part of class loader sub system talked about the Loading of class files. Next task that is performed by the class loader sub system is Linking.

Linking 

It performs 3 activities:
  • Verification
  • Preparation
  • Resolution

Verification

  • It is the process of ensuring binary representation of class file (output of Loading) is correct or not. Correct means if .class file is properly formatted or not, and it is generated by valid compiler or not.
  • Internally Byte Code Verifier, which is part of Class Loader Sub System, is responsible for this activity.
  • If verification fails, then it will throw the run-time exception, java.lang.VerifyError.

Preparation

  • In preparation phase, JVM will allocate memory and assign default values for class level static variables. For example:
    • For int --> 0
    • For double --> 0.0
    • For boolean -->false
    • For object --> NULL
  • It is important to note here that only default values are assigned in this phase, actual values (as defined in the class will be assigned in initialization phase. That means if a class variable is declared as,  private static int count = 10, 0 will be assigned in the preparation phase.

Resolution

  • All symbolic references are replaced with original direct references from method area. (Method area will be explained in coming articles). For example, consider following code:
 class Test {  
      public static void main(String[] args) {  
           String name = new String("Java Territory");  
           Student s1 = new Student();  
      }  
 }
  • In the above example, class loader sub system loads Test.class, String.class, Student.class and Object.class. The names of these classes are stored in constant pool of Test class.
  • In Resolution phase, these names are replaced with actual references from the method area of JVM.
After Linking is done, Initialization of class files are done.

Intialization
  • After Loading and Linking of class files are done, JVM will assign original values (as declared in the class file) to the class level static variables.
  • Also, static blocks are executed during this phase.
Following diagram explains the functions performed by Class Loader Sub System:
If any error comes Loading, Linking or Initialization, JVM will raise runtime exception, java.lang.LinkageError.

VerifyError is a child class of LinkageError.

This is all for Class Loader Sub System. In next article, I will talk about the types of Class Loaders. Please post your inputs in the comments section.

If you like reading our article, follow us +Java Territory / facebook to stay connected and get notifications for new articles.

0 comments:

Post a Comment