manage conflict on java classpath

2019-04-25 10:57发布

问题:

I expose my context :

I have two Java programs that run on a unique Weblogic Server : program A and program B. These ones are launched by two ksh :

programA.ksh and programB.ksh

Both need C.jar but in different versions (but with exactly the same package and classes) :

  • program A need C-1.0.jar
  • program B need C-2.0.jar

I precise that both programs share the same weblogic classpath.

So, my classpath contains in that order :

.....

C-1.0.jar

C-2.0.jar

.....

How can I do so that each program finds its good library ?

For instance, with my actual configuration, program B will always use C-1.0.jar instead of C-2.0.jar because of the priority position on classpath.

回答1:

If you launch two separate instances of the JVM for the two programs, then don't use the same classpath! Isn't that obvious?

Are you perhaps using the CLASSPATH environment variable? That is a very old, outdated practice and you should not do it. use the -classpath command line parameter, that way you can easily use different classpaths for the two programs.

Old answer: Assuming that you're talking about threads rather than processes:

The best solution would be to fix A, B or C so that both A and B can use the same version of C.

Or, if the two versions of C actually have intentionally different behaviour, use a different package or class names for them.

Only if you cannot change A, B or C should you consider the technical solution of writing a wrapper that uses different classloaders for A and B so that they will see different versions of C.



回答2:

Basically you cannot do this (simply). Take a look at http://en.wikipedia.org/wiki/Java_Classloader#JAR_hell, where they explain that the standard Java classloader cannot do this.

You can either run the two processes on different VMs, or go into a lot of classloader hell...



回答3:

You will have to make sure that only one library is present on classpath.

Simplest way is to create 2 lib directories with correct dependencies and reference all jars from there in your startup script for respective process.

This simple shell script will do this for you automatically:

MY_CLASSPATH=.

for i in /path/to/A/lib/*.jar
do
  MY_CLASSPATH=$MY_CLASSPATH:$i
done

java -cp $MY_CLASSPATH my.main


回答4:

I would assume that these are Java web apps if they're running on WebLogic, they ought to be in WAR files. There won't be any collision if each one puts their respective JAR versions in the WEB-INF/lib of their WAR file.