Tuesday, 28 November 2017

Core Java | Java Class loader

What is Java ClassLoader?

As we know Java Program runs on Java Virtual Machine (JVM) when we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled the program and stores it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.

The Java Classloader is a part of the JRE that dynamically loads Java classes into the JVM. Usually, classes are only loaded on demand. The Java runtime system does not need to know about files and file systems because of class loaders. It is one of the crucial but rarely used components of Java in Project Development.

JVM uses three class loaders

1. Bootstrap class loader
2. Extensions class loader
3. System class loader

Bootstrap class loader
It loads the core Java libraries located in the /jre/lib directory. This class loader, which is part of the core JVM, is written in native code.

Extensions class loader
The extensions class loader loads the code in the extensions directories (/jre/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.

System class loader
It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options. This is implemented by the sun.misc.Launcher$AppClassLoader class.

How does Java ClassLoader Work?

1. When JVM requests for a class, it invokes the loadClass function of the ClassLoader by passing the fully classified name of the Class.

2. loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not.

3. It’s required to avoid loading the class multiple times. If the Class is not already loaded, then it will delegate the request to parent ClassLoader to load the class. If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.

ClassLoader Parent

All class loaders except bootstrap class loader have a parent class loader. This parent is not as in the parent-child relationship of inheritance. Every class loader instance is associated with a parent class loader.

When a class loader is entrusted with the responsibility of loading a class, as a first step it delegates this work to the associated parent class loader. Then this parent class loader gets the instruction and sequentially it delegates the call to its parent class loader. In this chain of hierarchy, the bootstrap class loader is at the top.

When a class loader instance is created, using its constructor the parent classloader can be associated with it.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...