Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of different class loaders in java

I have read that there are different class loaders in java, the one is primordial class loader and there are custom class loaders as well, so I want to understand why primordial class loader is not able to serve all classes in java? Why is there need for other class loaders?

like image 387
Ankit Zalani Avatar asked Nov 28 '13 07:11

Ankit Zalani


2 Answers

The main need is isolation.

Let's say there are 3 applets on a page, each using a different version of the library foo.jar. You want each of those applets to run with its own version of the library, and to make sure it doesn't walk on another applet's toes. This is accomplished thanks to different class loaders.

The same goes for web applications deployed on a single container. The Java container is started without any app deployed, and then an app is deployed. You want the container to be able to load classes from a location it didn't even know about when it was started. And if another webapp is deployed, you want this other app to have its own classes and libraries, that are different and isolated from the classes and libraries of the first app.

Another need is to be able to load classes from various locations: the file system, but also URLs, databases, or whatever.

like image 168
JB Nizet Avatar answered Oct 02 '22 01:10

JB Nizet


There are many practical situations in which you want features beyond what the system class loader provides:

  1. You can give access to custom class sources (e.g., via http)
  2. You can cache blocks of data (e.g., 'if this class is needed, then let me pre-load these other classes')
  3. You can incorporate security protocols that prevent the loading of certain classes
  4. You can keep statistics of what classes are used, to later optimise your jar archives
  5. You can perform bytecode transformations ('load-time weaving') while loading the classes, e.g., to modify classes that fit a certain pattern. Aspect-Oriented Programming implementations can use this technique.

The final point is particularly powerful (and has been the main reason for why I have used them). Since Java bytecode is universal across platforms, you can use it to instrument classes on any system: measure which methods are called, suppress security-critical calls, divert System.out accesses to your own custom logging routines, or perform advanced dynamic bug-testing routines.

like image 43
creichen Avatar answered Oct 02 '22 02:10

creichen