Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why jvm has many clasloaders? why not one?

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?

like image 821
liuxiaori Avatar asked Mar 08 '12 09:03

liuxiaori


People also ask

Can you have more than one ClassLoader in Java?

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.

How many class loaders are present in JVM?

When the JVM is started, three class loaders are used: Bootstrap class loader. Extensions class loader. System class loader.

Does JVM load all classes?

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.)

How many types of class loaders are there in Java?

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.


2 Answers

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.

like image 125
JB Nizet Avatar answered Sep 22 '22 00:09

JB Nizet


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.

like image 31
user1252434 Avatar answered Sep 19 '22 00:09

user1252434