TExcelTAD
Home › Java Builds: Maven & Gradle › Version Mediation: Nearest Wins

Version Mediation: Nearest Wins

Two of your dependencies need the same library in different versions. The classpath can hold only one (remember first match wins), so the build tool must pick. This is the diamond dependency problem, and Maven's answer surprises almost everyone the first time: it doesn't pick the newest version, it picks the nearest.

The rule

Maven resolves the graph into a tree and, for each groupId:artifactId, keeps one version:

  1. Nearest definition wins: the version declared closest to your project (fewest hops) is used.
  2. First declaration wins: at equal depth, the dependency declared first in the POM wins.
  3. Versions are not compared. 1.0 beats 2.0 if it is nearer.

Building a conflict

To see it for real, the session creates four tiny libraries in the group org.acme and installs them into the local repository:

  • text-util in 1.0 (Text.trim) and 2.0 (adds Text.shout);
  • alpha uses text-util 1.0;
  • gamma uses text-util 2.0 and calls shout;
  • beta uses gamma.

Our app depends on beta and alpha. So text-util 1.0 is two hops away (app → alpha → text-util) and 2.0 three hops (app → beta → gamma → text-util).

bash · try it yourself
newlib() {   # newlib <folder> <artifactId> <version> <dependency XML>
  mkdir -p $1/src/main/java/lib
  cat > $1/pom.xml <<POM
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.acme</groupId><artifactId>$2</artifactId><version>$3</version>
  <properties><maven.compiler.release>21</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
  <dependencies>$4</dependencies>
</project>
POM
}
dep() { echo "<dependency><groupId>org.acme</groupId><artifactId>$1</artifactId><version>$2</version></dependency>"; }

newlib text-util-1.0 text-util 1.0 ""
echo 'package lib; public class Text { public static String trim(String s) { return s.strip(); } }' > text-util-1.0/src/main/java/lib/Text.java
newlib text-util-2.0 text-util 2.0 ""
cat > text-util-2.0/src/main/java/lib/Text.java <<'SRC'
package lib;
public class Text {
    public static String trim(String s) { return s.strip(); }
    public static String shout(String s) { return s.toUpperCase() + "!"; }
}
SRC
newlib alpha alpha 1.0 "$(dep text-util 1.0)"
echo 'package lib; public class Alpha { public static String hello() { return Text.trim("  alpha  "); } }' > alpha/src/main/java/lib/Alpha.java
newlib gamma gamma 1.0 "$(dep text-util 2.0)"
echo 'package lib; public class Gamma { public static String hello() { return Text.shout("gamma"); } }' > gamma/src/main/java/lib/Gamma.java
newlib beta beta 1.0 "$(dep gamma 1.0)"
echo 'package lib; public class Beta { public static String hello() { return Gamma.hello(); } }' > beta/src/main/java/lib/Beta.java
for d in text-util-1.0 text-util-2.0 alpha gamma beta; do (cd $d && mvn -q install); done

mkdir -p app/src/main/java/demo && cd app
cat > src/main/java/demo/Main.java <<'SRC'
package demo;
public class Main {
    public static void main(String[] args) {
        System.out.println(lib.Alpha.hello());
        System.out.println(lib.Beta.hello());
    }
}
SRC
newlib . app 1.0 "$(dep beta 1.0) $(dep alpha 1.0)"
mvn -q compile
mvn -o dependency:3.11.0:tree -Dverbose | sed -n '/--- dependency/,/^\[INFO\] ---/p' | sed '1d;$d;s/^\[INFO\] //'
java -cp "target/classes:$(mvn -q -o dependency:3.11.0:build-classpath -Dmdep.outputFile=/dev/stdout)" demo.Main
org.acme:app:jar:1.0
+- org.acme:beta:jar:1.0:compile
|  \- org.acme:gamma:jar:1.0:compile
|     \- (org.acme:text-util:jar:2.0:compile - omitted for conflict with 1.0)
\- org.acme:alpha:jar:1.0:compile
   \- org.acme:text-util:jar:1.0:compile
alpha
Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.String lib.Text.shout(java.lang.String)'
	at lib.Gamma.hello(Gamma.java:1)
	at lib.Beta.hello(Beta.java:1)
	at demo.Main.main(Main.java:5)
  • -Dverbose shows the losers: text-util:2.0 … omitted for conflict with 1.0.
  • The build is green. Compilation only needs alpha and beta's public API, and nothing checks that gamma was compiled against a text-util with shout.
  • At run time gamma calls Text.shout, the JVM finds Text from 1.0, and the program dies with NoSuchMethodError. This is the classic symptom of a mediation problem, and it often shows up only in production code paths.

Fixing it

There are three tools, from best to worst:

Fix How Effect
dependencyManagement pin text-util to 2.0 in <dependencyManagement> every occurrence in the tree, at any depth, uses 2.0
Direct declaration add text-util 2.0 to your own <dependencies> depth 1 is always nearest; but now you "use" a library you don't call
Exclusion <exclusions> on alpha's dependency removes 1.0 from alpha's subtree, so 2.0 is the only candidate

The managed version is the usual answer, and it's what the BOM lesson builds on. Same setup, plus five lines:

bash · try it yourself
newlib() {
  mkdir -p $1/src/main/java/lib
  cat > $1/pom.xml <<POM
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.acme</groupId><artifactId>$2</artifactId><version>$3</version>
  <properties><maven.compiler.release>21</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
  $5
  <dependencies>$4</dependencies>
</project>
POM
}
dep() { echo "<dependency><groupId>org.acme</groupId><artifactId>$1</artifactId><version>$2</version></dependency>"; }
newlib text-util-1.0 text-util 1.0 ""
echo 'package lib; public class Text { public static String trim(String s) { return s.strip(); } }' > text-util-1.0/src/main/java/lib/Text.java
newlib text-util-2.0 text-util 2.0 ""
echo 'package lib; public class Text { public static String trim(String s) { return s.strip(); } public static String shout(String s) { return s.toUpperCase() + "!"; } }' > text-util-2.0/src/main/java/lib/Text.java
newlib alpha alpha 1.0 "$(dep text-util 1.0)"
echo 'package lib; public class Alpha { public static String hello() { return Text.trim("  alpha  "); } }' > alpha/src/main/java/lib/Alpha.java
newlib gamma gamma 1.0 "$(dep text-util 2.0)"
echo 'package lib; public class Gamma { public static String hello() { return Text.shout("gamma"); } }' > gamma/src/main/java/lib/Gamma.java
newlib beta beta 1.0 "$(dep gamma 1.0)"
echo 'package lib; public class Beta { public static String hello() { return Gamma.hello(); } }' > beta/src/main/java/lib/Beta.java
for d in text-util-1.0 text-util-2.0 alpha gamma beta; do (cd $d && mvn -q install); done

mkdir -p app/src/main/java/demo && cd app
printf 'package demo;\npublic class Main { public static void main(String[] a) { System.out.println(lib.Alpha.hello()); System.out.println(lib.Beta.hello()); } }\n' > src/main/java/demo/Main.java
newlib . app 1.0 "$(dep beta 1.0) $(dep alpha 1.0)" \
  "<dependencyManagement><dependencies>$(dep text-util 2.0)</dependencies></dependencyManagement>"
mvn -q compile
mvn -o dependency:3.11.0:tree -Dverbose | sed -n '/--- dependency/,/^\[INFO\] ---/p' | sed '1d;$d;s/^\[INFO\] //'
java -cp "target/classes:$(mvn -q -o dependency:3.11.0:build-classpath -Dmdep.outputFile=/dev/stdout)" demo.Main
org.acme:app:jar:1.0
+- org.acme:beta:jar:1.0:compile
|  \- org.acme:gamma:jar:1.0:compile
|     \- (org.acme:text-util:jar:2.0:compile - version managed from 2.0; omitted for duplicate)
\- org.acme:alpha:jar:1.0:compile
   \- org.acme:text-util:jar:2.0:compile (version managed from 1.0)
alpha
GAMMA!

The tree now says version managed from 1.0, and both libraries run against 2.0. Here 2.0 is backwards compatible with 1.0 (it only added a method); if it weren't, no choice of version could make both alpha and gamma happy, and you'd need a newer alpha.

A model of the two strategies

Maven picks the nearest; Gradle (as you'll see in Dependency Configurations & Conflicts) picks the highest. Both walk the graph breadth-first; only the choice differs:

python · try it yourself
GRAPH = {   # artifact@version -> its dependencies, in declaration order
    "app@1.0": ["beta@1.0", "alpha@1.0"],
    "beta@1.0": ["gamma@1.0"],
    "alpha@1.0": ["text-util@1.0"],
    "gamma@1.0": ["text-util@2.0"],
    "text-util@1.0": [], "text-util@2.0": [],
}

def vkey(v):
    return tuple(int(x) for x in v.split("."))

def resolve(root, strategy):
    chosen, queue = {}, [(root, 0)]
    while queue:                        # breadth-first: nearer nodes are seen first
        node, depth = queue.pop(0)
        name, version = node.split("@")
        if name in chosen:
            old = chosen[name]
            if strategy == "highest" and vkey(version) > vkey(old):
                chosen[name] = version  # Gradle: a newer request upgrades the module
            continue                    # Maven: the first (nearest) one stays
        chosen[name] = version
        queue += [(d, depth + 1) for d in GRAPH[node]]
    return chosen

print("maven (nearest):", resolve("app@1.0", "nearest"))
print("gradle (highest):", resolve("app@1.0", "highest"))
maven (nearest): {'app': '1.0', 'beta': '1.0', 'alpha': '1.0', 'gamma': '1.0', 'text-util': '1.0'}
gradle (highest): {'app': '1.0', 'beta': '1.0', 'alpha': '1.0', 'gamma': '1.0', 'text-util': '2.0'}

The model is simplified (real Gradle re-resolves the subtree of an upgraded module, and Maven also applies dependencyManagement and exclusions), but the difference is real: the same graph produces different classpaths in the two tools. That matters when you migrate.

Test yourself

Your app gets lib:1.0 at depth 2 and lib:3.0 at depth 3. Which version does Maven use?

  1. 3.0, the newest
  2. 1.0, the nearest
  3. Both
  4. It fails the build

Two conflicting versions are both at depth 2. How does Maven break the tie?

  1. Highest version
  2. The dependency declared first in the POM wins
  3. Alphabetical order
  4. It asks you

A green Maven build fails at run time with NoSuchMethodError in a library class. What is the likely cause?

  1. A compiler bug
  2. Mediation picked an older version of a transitive dependency than the calling library was compiled against
  3. The JVM is too new
  4. A missing test dependency