JAR依赖加载至内存的重复依赖问题:同版本依赖会被加载两次吗?
Great question! Let's break this down based on how Java handles class loading—since the answer depends entirely on whether you're running the jars in separate JVM processes or the same one. First, let's anchor ourselves to the core rule of Java class loading: A class is uniquely identified by its fully qualified name AND the class loader that loaded it. That's the key to unpacking this scenario.
1. Running a.jar and b.jar as separate JVM processes
If you launch them with two separate commands like:
java -jar a.jar
and in another terminal:
java -jar b.jar
Each command spins up its own independent JVM instance. Every JVM has its own class loader hierarchy, method area, and isolated memory space.
In this case, c.jar will be loaded twice—once in each JVM process. The two instances of c.jar's classes have no connection to each other; they don't share memory, state, or class definitions. This is the most common scenario when running two distinct Java applications side by side.
2. Loading both jars in the same JVM process
If you're running them within a single JVM (e.g., adding both jars to the classpath and launching a main class that uses both, or using custom class loaders to load them), the answer splits into two subcases:
a. Using the same class loader for both jars
Suppose you launch with a command like:
java -cp a.jar:b.jar com.example.MainApp
Here, the system class loader handles loading classes from both jars. When it first encounters a class from c.jar (say, from a.jar first, based on classpath order), it loads that class and caches it.
When it later tries to load the same fully qualified class from b.jar, it checks its cache first, sees the class is already loaded, and skips reloading it. So c.jar is loaded only once in this scenario.
b. Using different class loaders for each jar
This is typical in environments like application servers (e.g., Tomcat, WildFly) where different web applications get their own dedicated class loaders. If a.jar is loaded with ClassLoader A and b.jar with ClassLoader B:
Even though the classes from c.jar are identical in version, they will be loaded twice. Each class loader maintains its own cache, and the JVM treats classes from different loaders as distinct types (even with the same fully qualified name). You'll end up with two separate copies of c.jar's classes in memory.
- Separate JVM processes:
c.jarloads twice - Same JVM + same class loader: loads once
- Same JVM + different class loaders: loads twice
内容的提问来源于stack exchange,提问作者Amr Ashraf

