Skip to content

[Bug] Memory Leak Risk in SingletonScope via Anonymous Provider (Implicit Outer Reference) #1929

@QiuYucheng2003

Description

@QiuYucheng2003

Issue Summary

The scope() method in com.google.inject.internal.SingletonScope returns an anonymous Provider instance. This architectural choice introduces a structural memory leak risk, specifically the "Deadly Embrace" pattern associated with non-static inner classes.

Root Cause Analysis

In Java, the anonymous Provider implicitly holds a strong reference to its enclosing instance (SingletonScope.this). Guice's internal context management relies heavily on ThreadLocal structures (e.g., for cycle detection locks).

When this anonymous Provider is captured within a thread-bound context, it establishes a persistent retention chain:
Thread -> ThreadLocalMap -> Anonymous Provider (Inner) -> SingletonScope (Outer).

Impact

In environments utilizing thread pools (where threads are long-lived), this reference chain prevents the Garbage Collector from reclaiming the SingletonScope and its associated injector graph. This results in an unresolvable topological black hole ("拓扑环状黑洞") causing severe memory leaks over time.

Proposed Solution

Refactor the anonymous Provider inside the scope() method into a static nested class. Any state required from the SingletonScope should be explicitly passed via the constructor. This will break the implicit strong reference to SingletonScope.this and allow the GC to function correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions