I am learning ClassLoader
in Java, then I want to know, why JVM has many classloaders, why not only one? The one first load <Java_Runtime_Home>/lib
, then load <Java_Runtime_Home>/lib/ext
, and last load classpath
.
If you have custom classloader, the system's first.
Somebody can tell me why JVM has many classloaders?
There can be multiple classloaders in a normal Java program. The one that loads your main class, ClassLoader , is the default one, and from your code, you can create and use as many classloaders as you like.
When the JVM is started, three class loaders are used: Bootstrap class loader. Extensions class loader. System class loader.
It loads the system classes required to run the JVM itself. You can expect all the classes that were provided with the JDK distribution to be loaded by this class loader. (A developer can expand the set of classes that the bootstrap class loader will be able to load by using the -Xbootclasspath JVM option.)
As we can see, there are three different class loaders here: application, extension, and bootstrap (displayed as null). The application class loader loads the class where the example method is contained.
One very useful application is to be able to deploy several web applications into a single Java EE server.
Each application might use different versions of the same libraries, and must thus have a different classloader from the others in order to be able to have different versions of the same classes in a single JVM.
There are several reasons to support more than one classloader.
First: separation of classes. Imagine an application server. Multiple independent projects may include the same libraries. If each application has its own classloader they can load different versions without collision and AFAIK static fields are instantiated per classloader.
Second: classloaders can be overwritten to change the classes. A class loader can enhance the classes during load time. Useful for aspect oriented programming (AspectJ) or adding debug or profiling code. An easy way to modify only one library but not the other is loading it through different classloaders.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With