Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing dependencies to multiple versions of a library in Java and Eclipse

In the Eclipse environment I have project A. A has dependencies to projects or libraries B and C. (does not make a difference if they are projects or libraries) B has dependency on LibX.v1 and C has dependency to LibX.v2. During runtime, A will need B.jar and C.jar. Also classes in B.jar will need LibX.v1 and classes in C.jar will need LibX.v2 . Being the different versions of the same library, LibX.v1 and LibX.v2 has same classes, so it is possible that a class may be loaded from the wrong version of the library in the runtime, causing lots of trouble. How do I manage these kind of situations?

Kind regards Seref

like image 809
mahonya Avatar asked Jan 19 '10 17:01

mahonya


2 Answers

Really, you don't. Most Java classloaders don't give any guarantees about the order in which libraries will be loaded, so you really need to be sure not to duplicate dependencies on your classpath. I would check if B or C could be updated to a newer version, or if LibX is fully backward-compatible.

Edit: actually, I found something that may help you. It's called OSGi, and I haven't used it, but it seems like it might do what you're trying to do. Here is a link to an intro article.

like image 195
danben Avatar answered Nov 16 '22 23:11

danben


you'll need to use a 'multiple classloader' mechanism (which is what OSGI is capable of). In such a scenario the classloader for class B can only see LibX.v1, while classloader C only sees LibX.v2. You can it do it with OSGI, but OSGI is much more than this and it's not trivial to get started with.

another plug-in framework is JPF, which also offers more than just using multiple classloaders. i think they both use the principle of 1 classloader per plug-in (module, whatever, ...)

maybe have a look at classworlds. I think it's possible to do it with this library. the benefit is that it focuses on the classloading aspect. documentation is not so good. classworlds uses the notion of class realms. take a look at the API Usage example on the site. i'll add an example here if i find one. anyway, no trivial solution for this i think

solving it with dependency management is the best solution of course, but it's not always possible.

like image 4
Stefan De Boey Avatar answered Nov 17 '22 01:11

Stefan De Boey