简体   繁体   中英

ClassNotFoundException after replacing a jar in classpath

I have a java process running with two jar files in the classpath namely
- A.jar
- B.jar
While the process was running, I replaced the B.jar with another B.jar which I updated with some files. Now in my process, I see some ClassNotFoundException s for the classes in the B.jar. I don't understand what is happening here. I thought the jars would be loaded when the java process was started. If that is the case why is it happening? Can somebody help me with this?? I know if I restart the process, everything will be fine. But I am curious to know the reason behind this.

Classes in a JAR file are loaded when they're first used , not at JVM startup. By replacing B.jar while the application is running, if you've removed classes that are referred to by others, you will get a ClassNotFoundException .

This can also happen in Java 7 if a class that you haven't used for a while has been garbage collected. The JVM will attempt to re-load it, and find that it is no longer in the classpath. This can also happen in earlier versions of Java if you're using the -XX:+CMSClassUnloadingEnabled startup option.

JVM supports static and dynamic loading of classes. JVM will load at startup all classes that are linked explicitely, but won't "discover" classes that are loaded dynamically at Runtime, via reflection for example. If you're doing a Class.forName("org.package.mySuperClass") in your code, and if your SuperClass is never linked by other pieces of code, it will be loaded at call time. If your jar containing this class has been removed from the classpath before the call, a ClassNotFoundException will be thrown

Note that a lot of modern framework use dynamic loading (even dynamic compilation that links to classes in classpath that were not linked before), and it's diffcult (and uncertain) to know which ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM