Sub topic 1
Why modules: the problems with the classpath
The Java Platform Module System (JPMS) arrived in Java 9. Before you write a module-info.java, you need to know what it replaces. This chapter covers the problems the classpath has, how each one shows up in real projects, and which part of JPMS addresses it.
Prerequisites
This chapter assumes you already know:
- Java syntax, packages, and the access modifiers
public,protected, andprivate. - How to compile and run programs with
javacandjava. - What a JAR file is and how
-cp(the classpath) tells the JVM where to find classes. - The basics of reflection and interfaces.
You do not need any module knowledge. The later chapters introduce module-info.java and the module path.
How the classpath works
The classpath is an ordered list of directories and JAR files. When the JVM needs a class, the class loader searches the entries in order and takes the first match. Nothing records which JAR depends on which, and nothing records which packages a JAR intends to share.
In effect, the classpath is one flat pool of classes.
This simple design causes the problems below.
Problem 1: public means public to everyone
In Java 8 and earlier, public meant "visible to every class in the program". A library author who wanted to share a class between two of the library's own packages had to make it public. That also exposed it to every user of the library.
Convention filled the gap. Names like internal or impl in a package signaled "do not use". Nothing enforced the convention, so applications came to depend on it.
The JDK had the same problem. Classes such as sun.misc.Unsafe and com.sun.* were public in practice. Frameworks used them, and the JDK team could not change or remove them without breaking those frameworks.
Reflection made things worse. setAccessible(true) let any code read or write private fields of any class, including JDK classes.
JPMS answer: a module chooses which packages it exports. Everything else is inaccessible to other modules, even if the classes are public. This is called strong encapsulation.
Problem 2: JAR hell and version conflicts
Suppose your application uses library A and library B. A needs util 1.0 and B needs util 2.0. Both versions contain the same class names. The classpath keeps whichever JAR comes first and silently ignores the other.
The following script reproduces this:
mkdir -p v1/com/example v2/com/example app
cat > v1/com/example/Lib.java <<'EOF'
package com.example;
public class Lib {
public static String version() { return "1.0"; }
}
EOF
cat > v2/com/example/Lib.java <<'EOF'
package com.example;
public class Lib {
public static String version() { return "2.0"; }
}
EOF
cat > app/Main.java <<'EOF'
public class Main {
public static void main(String[] args) {
System.out.println(com.example.Lib.version());
}
}
EOF
javac -d v1/out v1/com/example/Lib.java
javac -d v2/out v2/com/example/Lib.java
javac -cp v1/out -d app/out app/Main.java
java -cp app/out:v1/out:v2/out Main # prints 1.0
java -cp app/out:v2/out:v1/out Main # prints 2.0On Windows, use ; instead of : as the classpath separator.
The program is identical in both runs. Only the order of entries changed, and that changed the behavior. No warning appears. Real failures show up later as NoSuchMethodError or AbstractMethodError, when a class compiled against version 2 runs against version 1.
JPMS answer: the module system refuses to start if two modules in the same layer contain the same package (see "Problem 4"). It does not by itself pick versions. It makes the conflict visible instead of hiding it.
Problem 3: missing dependencies appear late
A JAR does not declare what it needs. The JVM only discovers a missing class when some code path first touches it. The program can start fine, run for hours, and then fail:
Exception in thread "main" java.lang.NoClassDefFoundError: org/example/ParserBuild tools such as Maven and Gradle declare dependencies at build time. That information is not available to the JVM at run time.
JPMS answer: a module declares its dependencies with requires. At startup the runtime checks that every required module is present, and it fails immediately if one is missing. The error names the module, which is far easier to act on than a stray NoClassDefFoundError.
Problem 4: split packages and accidental overlap
Two JARs can contain classes in the same package, for example com.acme.util. On the classpath that is legal and sometimes intentional. Package-private access works across the JARs, because the classes share a runtime package.
It also lets one JAR shadow another's classes, or lets code in a JAR you do not control reach package-private members of your classes.
JPMS answer: a package belongs to exactly one module within a layer. Packages that are split across modules are an error. Chapter "Split packages and how to fix them" covers the fixes.
Problem 5: a monolithic platform
Before Java 9, the whole JDK was packaged mostly in rt.jar. That one file held roughly 20,000 classes covering Swing, CORBA, XML, JDBC, and more. A tiny command-line tool and a desktop application both carried and loaded all of it.
This hurt in three ways:
- Deployments were large, which mattered for containers and embedded devices.
- Startup time included scanning and verifying more than the program needed.
- The JDK team could not remove obsolete APIs, because any program might still use them.
JPMS answer: the JDK itself is split into modules such as java.base, java.sql, and java.desktop. A program can depend on only what it needs. The jlink tool, covered near the end of this tutorial, builds a runtime that contains just those modules.
Summary of problems and answers
| Classpath problem | Symptom | JPMS feature |
|---|---|---|
| Every `public` type is global | Apps depend on internal classes | `exports` and strong encapsulation |
| Duplicate classes, first wins | Behavior depends on JAR order | One package per module, checked at startup |
| Undeclared dependencies | `NoClassDefFoundError` at run time | `requires`, checked at startup |
| Split packages | Shadowing, accidental access | Split packages rejected |
| Monolithic JDK | Large, slow deployments | Modular JDK, `jlink` |
A first look at the fix
You will write modules in the next chapter. This descriptor shows how little it takes to state a dependency and an API:
module com.example.greeter {
requires java.logging;
exports com.example.greeter.api;
}Reading it tells you three things without opening any other file:
- The module depends on
java.logging. - Other modules may use types in
com.example.greeter.api. - Every other package in the module is hidden.
On the classpath, none of that information exists.
What modules do not solve
Be realistic about the limits:
- JPMS has no notion of version numbers in
module-info.java. It cannot loadutil 1.0andutil 2.0side by side in one layer. Module layers can do that, but they are an advanced feature. - Modularizing a large application takes work, especially when third-party libraries are not yet modular.
- Strong encapsulation can break libraries that rely on deep reflection. Migration chapters cover the
--add-opensflag and theopensdirective.
Exercise
Your application starts and runs normally with libraries A and B on the classpath. After a build change reorders the classpath, one feature starts throwing NoSuchMethodError. Name the classpath problem and say which JPMS behavior would have exposed it earlier.
Show answer
This is a version conflict ("JAR hell"). Both libraries pull in different versions of the same dependency, and the classpath silently uses whichever copy comes first, so the reordering changed which version loaded. With modules, the same package present in two modules in one layer is an error at startup, and the requires graph makes the conflict visible instead of silently picking a winner.
Exercise
A library has a public class com.acme.lib.internal.Cache that it never meant users to touch. Why can any application still call it on the classpath, and what does a module do to prevent that?
Show answer
On the classpath, public means accessible to all code, and no package-level export control exists. A module that does not list com.acme.lib.internal in an exports directive makes the package inaccessible to other modules, even though the class is still public.