Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How JVM works when two same jar be included in classpath

Tags:

java

It was a mistake of my co-worker: there was a jar named test.jar and he has fixed a bug of it. Then he re-compile the code and built a new jar named testnew.jar The problem was he put these two jar into one folder which in classpath. So when program was running, the behavior was a kind of mess. I didn't know what had happened but after removing test.jar, everthing was fine again.

So I'm wondering what's the behavior of JVM. Does it use the class file in first jar it meet? Or something else?

Thanks.

like image 487
XiaoYao Avatar asked Mar 18 '12 09:03

XiaoYao


2 Answers

Yeah, by default it uses classes from first jar. That's why you have to check library directory for duplicates. Happend so many times for me and my colleagues.

like image 189
mihn Avatar answered Sep 22 '22 16:09

mihn


As far as I can tell, it isn't defined.

Java has a pluggable classloader system, and thus the only way to know what will happen is to look at the documentation of the ClassLoader class, probably in particular the ClassLoader#findClass method, which doesn't define a behavior for this, and to look at the relevant sections of the JLS and JVM specs, neither of which seem to specify a constraint on class loaders in this regard. Thus, unless the behavior is documented by the class loader being used by your web container, you can't know for certain which class will be loaded.

The odds are that the first one found that matches the binary name of the class will be the one loaded, but there's a big difference between behavior we suppose to be the case, and behavior that is specified and/or documented.

like image 33
T.J. Crowder Avatar answered Sep 21 '22 16:09

T.J. Crowder