Course contentsShow
← Java
Lesson 2477 of 2,87047. Java Platform Module System (JPMS)Free lesson

Circular Dependencies and Why They're Forbidden

Learn why circular requires relationships are prohibited in JPMS and how to refactor around them.

Circular Dependencies and Why They're Forbidden

You'll learn why JPMS prohibits circular requires relationships and how to resolve them when they appear.

What Is a Circular Dependency?

A circular dependency occurs when Module A requires Module B, and Module B (directly or indirectly) requires Module A. In JPMS, this creates a cycle in the module graph that the module system refuses to load.

// com.example.alpha/module-info.java
module com.example.alpha {
    requires com.example.beta;  // Alpha needs Beta
}

// com.example.beta/module-info.java
module com.example.beta {
    requires com.example.alpha;  // Beta needs Alpha — CIRCULAR!
}

This will fail at compile time or runtime with an error like: java.lang.module.FindException: Cycle detected.

Why Are They Forbidden?

Circular dependencies create ambiguity in the module graph. The module system cannot determine a safe initialization order—which module should load first? This violates JPMS's goal of strong, predictable encapsulation.

Think of it like two people simultaneously asking each other for help to stand up. Neither can rise independently.

How to Refactor Around Them

1. Extract Common Code: Create a third module containing shared interfaces or utilities that both modules require.

module com.example.shared { }

module com.example.alpha {
    requires com.example.shared;
}

module com.example.beta {
    requires com.example.shared;
}

2. Merge Modules: If the circular dependency indicates tightly coupled code, consider combining them into a single module.

3. Use Service Providers: Decouple modules using the provides and uses directives to avoid direct requires relationships.

Key Takeaway:
JPMS forbids circular requires relationships to maintain a clear, acyclic module graph; refactor by extracting shared code, merging modules, or using service interfaces.