FOR DEVELOPERS

Guide to the Basics of ClassLoader

ClassLoaders in Java

ClassLoaders load Java classes dynamically during the runtime to Java Virtual Machine. ClassLoaders are also part of the JRE (Java Runtime Environment). This means JVM does not require knowledge about the files used to create the file systems to run Java applications.

You can’t upload Java class files in memory all at once. Instead, you need an application to load them. This is where the ClassLoaders come on the scene. ClassLoaders are responsible for loading the classes into memory.

In this blog, I will walk you through the basics of ClassLoader to help you land the best Java developer jobs.

Types of Java ClassLoader

Java ClassLoader

In Java, each ClassLoader has a predefined location from which it loads the class file. There are three kinds of ClassLoaders in Java:

Bootstrap ClassLoader

Java classes load by an instance of java.lang.ClassLoader. ClassLoaders are also classes themselves. So how does java.lang.ClassLoader load for the first time?

That's where the Bootstrap ClassLoader comes into the picture.

  • Bootstrap ClassLoader is the machine code that kickstarts the operation when JVM begins to run.
  • Its task is to load the first Java ClassLoader. It is not a Java class. Bootstrap ClassLoader loads the rt.jar file and other core libraries in the $JAVA_HOME/jre/lib directory.
  • Bootstrap ClassLoader is the parent of all ClassLoaders. It doesn’t have any parents.

It's also known as the Primordial ClassLoader.

Extension ClassLoader

Extension ClassLoader is the child of Bootstrap ClassLoader.

It handles the loading of core Java class extensions to ensure they are available to all programs running on the platform.
Extension ClassLoader loads classes from the $JAVA_HOME/lib/ext directory or other directory listed in the java.ext.dirs system property.
Its implementation is done by sun.misc.Launcher$ExtClassLoader in JVM.

System ClassLoader

This ClassLoader is the child of the Extension ClassLoader.

  • It loads application-level classes into the JVM. System ClassLoader loads class files from the classpath environment variable, -classpath, or -cp command-line options.
  • System ClassLoader is also known as the Application ClassLoader.
  • The implementation is done by sun.misc.Launcher$AppClassLoader class.

How ClassLoader works in Java

ClassLoader is a part of the JRE. When the JVM calls for a class, the ClassLoader attempts to locate the class and load the class's definition into runtime by using the fully qualified class name.

By using java.lang.ClassLoader.loadClass() method the class definition is loaded into the runtime. It loads the class using the fully qualified class name.

This loadClass() method then invokes the findLoadedClass() method. This method determines whether the class is already loaded or not. It is essential to ensure that the class is not loaded repeatedly.

If the class already exists, it delegates the request to the parent ClassLoader in order to start loading the class. If the ClassLoader cannot locate its class in the database, it uses java.net.URLClassLoader.findClass() method to find the classes within the system file.

If the last child ClassLoader cannot find or load the class, it throws java.lang.ClassNotFoundException or java.lang.NoClassDefFoundError.

Imagine that we have an application-specific class HelloWorld.class. The request to load these class files goes to the Application ClassLoader. The class is then delegated to the parent Extension ClassLoader. Additionally, it delegates to the Bootstrap ClassLoader.

Bootstrap will search for that class within rt.jar and, since the class is not present, it fails to load it. Now it requests transfer to Extension ClassLoader which searches for the directory jre/lib/ext, and attempts to find the class.

If the class is found there, the Extension ClassLoader loads the class. Application ClassLoader does not load the class. If the Extension ClassLoader is unable to load the class then the Application ClaasLoader loads it via CLASSPATH within Java.

Remember that Classpath is used for load class files, and PATH is used to find executables such as javac or java commands.

Principles of Java ClassLoader

Java ClassLoader works upon three main principles: Delegation, transparency, and uniqueness.

Delegation principle

It forwards class loading requests to the parent ClassLoader and loads the class only when the parent cannot locate or load the class.

Visibility principle

It allows the child class loader to view all classes loaded by the parent ClassLoader. However, the parent loader cannot see the classes loaded by the child class loader.

Uniqueness principle

It ensures no duplicate classes are loaded in the ClassLoader. The child ClassLoader must not reload the class already in the parent ClassLoader.

In the next section, let me introduce you to custom ClassLoader.

Custom ClassLoader

The built-in loader for classes is enough for most cases where files are already in the file system. However, in situations where we have to load classes from either the local drive or network, we might need to use custom ClassLoaders for classes.

In this part, we'll discuss different use cases for custom ClassLoaders.

Use cases of custom ClassLoaders

  • Offers modular architecture: It allows to define multiple ClassLoaders, which allows for modular architecture.
  • Avoidance of conflicts: clearly defines the boundaries of the class within the ClassLoader.
  • Versioning support: Allows different class versions for different modules within the same VM.
  • Memory management: Modules that are not used can be eliminated, which unloads the classes utilized by that module, and cleans memory.
  • Classloading from any location: Classes can be loaded from any location, such as databases or Networks.
  • Runtime reloading modified classes: Allows reloading a class runtime by creating the child ClassLoader of the actual ClassLoader that includes modifications of the classes.

Implementation of ClassLoader in Java

Let's take a look at how java.lang.ClassLoader implementation is done, and what are its functionalities. These concepts are important for cracking interviews for senior Java developer job roles.

loadClass(): This is the important method that takes the name of the class as a string, and it will return an instance of a class back. It is the class that ClassLoader has found on its classpath, and it will provide it so that an object can be created from it.

Implementation of ClassLoader in Java loadClass()

defineClass(): This method is similar to the loadClass method except that it uses a byte array as the argument, and creates an instance of the class using that byte array. It is slightly different from the loadClass method because loadClass must find the class to load it, whereas in defineClass the class itself is given as a byte array.

Implementation of ClassLoader in Java defineClass()

GetResource(): This method can be used to identify any issues that arise from loading the class since it will provide the URL when you provide the string name and package name. It will provide you with the exact location your class is loaded.

Implementation of ClassLoader in Java GetResource():

getparent(): It's the most important method to understand the structure of classLoader. ClassLoader does not have a flat structure. It has a child and parent hierarchy and different levels of structure.

ClassLoader in Java getparent()

Conclusion

Class loaders are necessary for the execution of a Java program. In this article, we've provided an informative overview of these ClassLoaders. We talked about the various kinds of classloaders, including Bootstrap, Extensions, and System.

Bootstrap acts as a parent to each of them; it is responsible for initially loading the JDK class library. Extensions and System, in contrast, are responsible for loading classes from the Java extensions directory and classpath, respectively.

You also learned the principles of ClassLoaders (visibility, delegation, and uniqueness) and how to carry out custom class loading in Java. If you’re an expert developer eager to work with Java we have just the right platform for you. Visit us at Turing.com to know more about your dream job.

Author

  • Soumyakanti

    Soumyakanti Ray

    Soumyakanti Ray is a writer, blogger, and SEO analyst with over nine years of experience. His work features in top publications like The Verge, India Today, and NDTV. He is a big-time foodie. He loves to play cricket, football, and video games in his free time.

Frequently Asked Questions

A ClassLoader is an object that loads Java classes dynamically during runtime in order to stop JVM from being aware that ClassLoader is a component of the Java Runtime Environment. It helps to make JVM life simpler. JVM loads classes into memory whenever needed by the application and doesn't load them all at one time. ClassLoader comes into it and loads the classes in memory.

A class is identified by its fully qualified name (package.classname). When the class is loaded into JVM it will have an entry for it as (package, classname, classloader). Therefore, the same class may be loaded twice by two different instances of ClassLoader.

Errors of type java.lang.NoSuchMethodError indicates class loading errors. This error is usually caused by the classes in the JAR file in the emitter clashing with classes that are used by the application server.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.