15

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
liuxiaori
  • 317
  • 2
  • 10

4 Answers4

21

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
6

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.

user1252434
  • 2,083
  • 1
  • 15
  • 21
5

enter image description here Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

Rakesh
  • 4,264
  • 4
  • 32
  • 58
4

It allows you to run multiple applications in the same JVM.

It also allows you to unload portions of code and upgrade them in a running system. (even if you only have one application)

You might find this information about OSGi useful http://www.javaworld.com/javaworld/jw-03-2008/jw-03-osgi1.html

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130