Skip to content

TypeLiteral configured in child Injector leaked into parent Injector #910

@moreginger

Description

@moreginger

Perhaps this behavior is known but I couldn't find any mention of it. This code...

 public static void main(final String[] args) {
    Injector parent = Guice.createInjector();

    parent.createChildInjector(createModule(new GiantObject("notleaked")));

    // GiantObject("notleaked") can be garbage collected.

    parent.createChildInjector(createTypeLiteralModule(new GiantObject("leaked")));

    // GiantObject("leaked") cannot be garbage collected.
  }

  private static AbstractModule createModule(final GiantObject o) {
    return new AbstractModule() {
      @Override
      protected void configure() {
        bind(GiantObject.class).toInstance(o);
      }
    };
  }

  private static AbstractModule createTypeLiteralModule(final GiantObject o) {
    return new AbstractModule() {
      @Override
      protected void configure() {
        bind(new TypeLiteral<GiantObject>() {
        }).toInstance(o);
      }
    };
  }

...puts a reference to the TypeLiteral in the parent Injector, and appears never to be garbage collected. JProfiler lists InheritingState/WeakKeySet in the first GC root. This leaks whatever is in scope for the TypeLiteral (i.e. the GiantObject("leaked") instance).

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