Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why delegate when loading classes in java

As the javase 7 documentation describes

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself.

Why ClassLoader delegates the search for the class or resource to its parent? What is the purpose or the advantage of doing so?

like image 405
Harsha Jayamanna Avatar asked Jan 13 '17 20:01

Harsha Jayamanna


1 Answers

There are several valid reasons for classloading delegation. I have listed them according to their priority(from my understanding):

Security

There are certain classes in Java which shouldn't be messed with. By having parent-first delegation model, JVM can be sure that it is executing only those classes and not the one loaded by custom classloaders.

Avoid duplicate class instances

Classloading is a costly operation as it requires reading data from external storage or network, parsing the bytecode, allocating memory and so on. So restricting the JVM to load the classes only once is one of the reasons. By forming classloader hierarchy with the parent-first rule will achieve this.

Class Scope

There are certain classes which are the core part of Java, like java.lang.*. These classes are part of Java language and will be used at almost all the places. Since a class is identified uniquely by its fully qualified name along with the classloader which loaded that class, it is important to have a single classloader to load such classes. Thus the bootstrap and extension classloader take care of this. Also, by loading the classes and resources at top level gives them a broader scope than loading at the bottom of the classloader hierarchy.

like image 129
code Avatar answered Sep 27 '22 18:09

code