Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two incompartible classes with same full name?

A problem: My application uses two libraries which use incompatible versions of a third library. Does someone know any method for classes isolation?

I have heard about class loaders, but I do not understand, how they could help - if we will load one version of class, we cannot load another - class is already loaded?

I also thinking about Spring, but do not know if it provides such isolation.

like image 292
Nulldevice Avatar asked Nov 04 '22 21:11

Nulldevice


1 Answers

ClassLoaders are basically the elements that gives meaning to classes in the JVM. They form a hierarchy for wich the root lies in the JVM and loads java classes. The ApplicationClassLoader is the first ClassLoader you have to consider, as it loads all the classes of your application.

When a class is loaded, all its references to other classes are resolved and theses classes are loaded. The JVM by default provides a system where classloaders ask their parent first to see if they have already loaded a class. If not, they search in their classpath

Two classes can be isolated if they live in 2 different classloader, and not in the app classloader. It's not difficult to do. You only have to create a classloader (like URLClassLoader) while specifying its parent and its classpath(the place where the bytecode is)

then, you tell him to load a class. It will ask its parent, and if the class is not loaded yet, it will search its classpath and load it. If you create another classloader attached to the same parent, the classes loaded by the first will never be seen by the seconds as they are siblings. And the second can loads a class with the same name without any problem

That's quite a good isolation

App Servers use another form of delegation to have a frank isolation between applications. they redefine a classloader extending, for example, URLClassLoader and reverse the delegation process by starting to search for classes in their classpath first, then ask to the parent

like image 55
Grooveek Avatar answered Nov 12 '22 16:11

Grooveek