Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are more class loaders needed?

I know that hierarchy of class loaders in java is :

1.Bootstrap class loader (in native code)
2. Extension class loader (sun.misc.Launcher$ExtClassLoader)
3. System class loader (sun.misc.Launcher$AppClassLoader class)
4. Custom class loaders (i.e. app server, ear classloader, war classloader)

It is not clear for me why additional child class loaders are needed. I could understand the need for 'pure java' class loader after the one in native code.
I have some thoughts of possible reasons but can someone provide me with clear explanation for this behavior / need for hierarchies of class loaders?
In general but applicable for j2ee as well.

like image 516
ps-aux Avatar asked Oct 04 '22 02:10

ps-aux


1 Answers

Classloaders are useful for providing a variety of behavior and for protecting different Java programs running in the same VM from each other. There are three major categories that come to mind:

  • Classloaders can implement the process of loading classes differently. For example, you might have a classloader that retrieves the bytecode for a class from some server and then installs it into the JVM, or you might have a classloader that actually generates the bytecode on the fly instead of reading it out of a file.
  • Classloaders can form partitions inside a single JVM so that different code "trees" can have different copies of classes with the same names. A common example of this is a servlet container like Tomcat, where several wars might be installed that all have different versions of a library (say, Apache Commons-Lang). OSGi also uses this approach to ensure that each bundle can only access the classes it's specifically requested and can't "leak" API.
  • Classloaders can be used to implement different policies about when to garbage-collect actual classes themselves. Using just the default classloader keeps classes around indefinitely, leading to the dreaded PermGen errors; an application that used lots of temporary classes (maybe ones generated on the fly) might want to make sure that they were freed when no longer necessary by using disposable classloaders.
like image 121
chrylis -cautiouslyoptimistic- Avatar answered Oct 13 '22 10:10

chrylis -cautiouslyoptimistic-