Class Loaders
Let’s take two simple Java Files as below
Helper.java
package com.mugil.org; public class Helper { public String getMessage() { return "Helper Method"; } }
TestHelper.java
package com.mugil.org; public class TestHelper { public static void main(String[] args) { Helper objHelper = new Helper(); System.out.println(objHelper.getMessage()); } }
How to Compile class in Command Prompt
Normally when you compile Java class the class files would be created in bin folder with
the folder structure same as package name bin->com->mugil->org.
When you want the .class to be created in a specific folder then use the below command
D:\java\ClassLoaders>javac -d classes -sourcepath src src\com\mugil\org\Helper.java
Classes folder should be created manually or it’s going to throw
javac: directory not found: classes
Before Running the code the Classpath needs to be set which could be done either globally
by adding to the System classPath or locally at the application level
To Set globally the following should be run in Command Prompt
D:\java\ClassLoaders>set CLASSPATH=classes
After this, the Java code can be run as below
D:\java\ClassLoaders>java com.mugil.org.TestHelper Helper Method
Setting Globally is not a good idea as other applications Classpath would be affected.If you
have set classpath globally chances are you may end up running wrong JAR file in the Classpath
The Better option is to set classpath while running the application itself
D:\java\ClassLoaders>java -cp classes com.mugil.org.TestHelper Helper Method
Now let’s see how to take .class files in some other folder or .class files in JAR folder to
To run the .class file in other folders along with the one we are running adding the .class files separated by semicolon would be an easy way
as below
D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper Helper Method
The Helper.class is moved to D:\class1 folder and TestHelper.class is in D:\java\ClassLoaders\classes folder
TestHelper.class needs Helper.class to run.
Now how about JAR Files
D:\class1>jar cvf helper.jar com\mugil\org\Helper.class added manifest adding: com/mugil/org/Helper.class(in = 296) (out= 227)(deflated 23%)
To run the classes in the JAR Files the same command applies.D:\class1 is the location where the JAR’s are located(helper.jar).
D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper Helper Method
Once the JAR is created the .class files can be deleted and added to lib folder
While Creating JAR make sure you maintain the folder structure.Creating JAR file without adding com\mugil\org folder will result in classNotFound Exception
D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes\lib\Helper.jar;D:\java\ClassLoaders\classes\; com.mugil.org.TestHelper
Class loaders are the part of the Java Runtime Environment that dynamically loads Java classes into the Java virtual machine. It is responsible for locating libraries, reading content and loading the classes contained within the libraries. When JVM is started three class loaders are used
How ClassLoaders works
- When JVM requests for a class, it invokes loadClass function of the ClassLoader by passing the fully classified name of the Class.
- loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. 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.
1. Bootstrap class loader (Written in C)
2. Extensions class loader (Written in Java)
3. System or Application class loader (Written in Java)
Apart from CLASSPATH java looks into two other locations to load the JAR Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib in JRE installation Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext
Bootstrap class loader
It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes
rt.jar is one of the JAR files in JRE Folder. You can see the content in rt.jar by renaming it into rt.jar.
rt.jar is loaded by the bootstrap class loader.
Extensions class loader
It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
You can add your JAR files like DB Connection JAR in the EXT folder and would be available to all application which runs on JVM
helper.jar added to ext folder
D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper Helper Method D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes; com.mugil.org.TestHelper Helper Method
Note:In the second statement the D:\class1 is missing which has the JAR files which is now moved to EXT folder.No need to specify the JAR files as JAR files in EXT are loaded by default
System (or) Application class loader
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Delegation of Classes
- Delegation Classes are classes which delegates the call to its Parent Class which inturn Delegates to its Parent
- Each class loader has a parent. Class Loaders may delegate to its Parent. Parent may or may not load the class
- Loaded classes are always cached
- Application loader asks the Extension Class loader which inturn asks Bootstap loader
- If Bootstap loader couldnt find the class it will send fail message which makes the Extension Class loader to search for classes within
- If Extension loader couldnt find the class it will send fail message to Application Class Loader and makes to search for classes within
- If Application Class loader couldnt find the class NoClassDefinition Error would be Displayed
import java.net.URLClassLoader; public class Delegation { public static void main(String[] args) { URLClassLoader classloader = (URLClassLoader)ClassLoader.getSystemClassLoader(); do { System.out.println(classloader); } while ((classloader = (URLClassLoader)classloader.getParent()) != null); System.out.println("Bootstrap ClassLoader"); } }
Output
sun.misc.Launcher$AppClassLoader@1497b7b1 sun.misc.Launcher$ExtClassLoader@749cd006 Bootstrap ClassLoader
To See the location of the Class Files loaded you can use the below code
. . do { System.out.println(classloader); for(URL url : classloader.getURLs()) System.out.println("\t %s"+ url.getPath()); } while ((classloader = (URLClassLoader)classloader.getParent()) != null); . .
Output
sun.misc.Launcher$AppClassLoader@1497b7b1 %s/D:/java/ClassLoaders/bin/ sun.misc.Launcher$ExtClassLoader@749cd006 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/access-bridge-64.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/dnsns.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/jaccess.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/localedata.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunec.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunjce_provider.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunmscapi.jar %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/zipfs.jar Bootstrap ClassLoader
In the above Output, you can see the Application Class Loaders loads the Java class from the Project Directory and EXT jars from the EXT C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/ Folder
Why we need Custom ClassLoader?
Whenever a class is referenced in a java program it is loaded using JVM’s bootstrap class loader. This often becomes a problem when two different classes with same name and same package declaration are to be loaded. For example relying on JVM’s class loader one cannot load two different versions of the same JDBC driver. The work around to this problem is lies in making a custom class loader and loading classes directly from JAR archives.
Other Reasons
- Better Memory Management Unused modules can be removed which unloads the classes used by that module, which cleans up memory.
- Load classes from anywhere Classes can be loaded from anywhere, for ex, Database, Networks, or even define it on the fly.
- Runtime Reloading Modified Classes Allows you to reload a class or classes runtime by creating a child class loader to the actual class loader, which contains the modified classes.Hot Deployment
- Provides Modular architecture Allows to define multiple class loader allowing modular architecture.
- Support Versioning Supports different versions of class within same VM for different modules. Multiple Version Support
- Avoiding conflicts Clearly defines the scope of the class to within the class loader.
- Class loading mechanism forms the basis of Inversion of Control
Simple URL Class Loader
In the below example we are using URL Class Loading method to load the Classes from the JAR file.We can load Classes from File Based URL or Network Based URL
We can also load class from DB
SimpleClassLoader.java
public class SimpleClassLoader { public static void main(String[] args) { URL url; try { url = new URL("file:///D:/jars/helper.jar"); URLClassLoader ucl = new URLClassLoader(new URL[]{url}); Class clazz = ucl.loadClass("com.mugil.org.Helper"); Object o = clazz.newInstance(); Helper objHelper = (Helper)o; System.out.println(o.toString()); System.out.println(objHelper.getMessage()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
Output
Helper Method com.mugil.org.Helper@4631c43f
Note: In the above example you can see the Typecasting from Object to Helper which again makes the code tightly coupled and defeats the purpose of the class loader dynamically loads Java classes into the Java Virtual Machine. To resolve this issue we can use Interface which is loaded by application class loader with the implementing class loaded by our own class loader.
Account.java
public interface Account { public Integer getInterestRate(); }
SavingsAccount.java
public class SavingsAccount implements Account { @Override public Integer getInterestRate() { return 10; } }
Implementation classes added to our JAR so it can be loaded by our Class Loader
D:\java\ClassLoaders\bin> jar cvf Accounts.jar com\mugil\org\SavingsAccount.class added manifest adding: com/mugil/org/SavingsAccount.class(in = 496) (out= 301)(deflated 39%)
CalculateInterest.java
public class CalculateInterest { public static void main(String[] args) { URL url; try { url = new URL("file:///D:/jars/Accounts.jar"); URLClassLoader ucl = new URLClassLoader(new URL[]{url}); Class clazz = ucl.loadClass("com.mugil.org.SavingsAccount"); Account o = (Account)clazz.newInstance(); System.out.println(o.toString()); System.out.println(o.getInterestRate()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
In the above code I can change the logic interest is calculated in the SavingsAccount and redeploy the JAR without taking effect in other parts of the program.
The above jar file could be loaded accross network by giving URL as below
. . URL url = new URL("http://localhost:8080/Accounts.jar"); . .
Multiple version Support of Same JAR
Java bytecode is universal across platforms, you can use it to instrument classes on any system: a measure which methods are called, suppress security-critical calls, divert System.out accesses to your own custom logging routines, or perform advanced dynamic bug-testing routines.
public static void main(String[] args) { try { URL url1 = new URL("file:///D:/jars/Accounts1.jar"); URLClassLoader ucl1 = new URLClassLoader(new URL[]{url1}); Class clazz1 = Class.forName("com.mugil.org.SavingsAccount", true, ucl1); Account quote1 = (Account) clazz1.newInstance(); URL url3 = new URL("file:///D:/jars/Accounts.jar"); URLClassLoader ucl3 = new URLClassLoader(new URL[]{url3}); Class clazz2 = Class.forName("com.mugil.org.SavingsAccount", true, ucl3); Account quote2 = (Account) clazz2.newInstance(); System.out.printf("clazz1 == clazz2? %b\n", clazz1 == clazz2); System.out.printf("quote1.class == quote2.class? %b\n", quote1.getClass() == quote2.getClass()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
Output
clazz1 == clazz2? false quote1.class == quote2.class? false