Why delegate when loading classes in java

How javase 7 documentation is described

The ClassLoader class uses the delegation model to search for classes and resources. Each instance of the ClassLoader class has an associated parent element of the loader class. When you are asked to find a class or resource, the ClassLoader class delegates the search for the class or resource to its parent class loader before trying to find the class or resource.

Why does ClassLoader delegate the search for a class or resource to its parent? What is the purpose or advantage of this?

+5
source share
1 answer

There are several good reasons for delegating at boot. I have listed them according to their priority (from my understanding):

Security

Java has certain classes that you cannot mix with. With a parent delegation model, the JVM can be sure that it only executes classes, not those loaded by custom class loaders.

Avoid duplicate class instances

Classloading is an expensive operation because it requires reading data from an external storage or network, parsing byte code, allocating memory, etc. Therefore, limiting the JVM to load classes only once is one reason. When creating a class loader hierarchy with the parent-first rule, this will be achieved.

Class scope

There are certain classes that are a major part of Java, for example java.lang.* . These classes are part of the Java language and will be used in almost all places. Since a class is uniquely identified by its full name along with the class loader that loads this class, it is important to have one class loader to load such classes. In this way, the classloader bootloader and extension loader will take care of this. In addition, when loading classes and resources at the top level give them a wider reach than loading at the bottom of the hierarchy of class loaders.

+2
source

Source: https://habr.com/ru/post/1262774/


All Articles