Search code examples
javaguicerestlet

guice injector getInstance of annotated singleton instance


I'm using Restlet with Guice.

A CachedThreadPool is definded in my Guice:

@Provides
@Singleton
@Named("name0")
public ExecutorService provideAutoDisconnectThreadPool () {
    return Executors.newCachedThreadPool();
}

Wanted to shutdown the threadPool when the server is stops, so in my restlet.Application, I use injector to get the instance:

@Override
public void stop() throws Exception {
    LOGGER.info("stopping...");
    // shutdown threadPool
    injector.getInstance(ExecutorService.class).shutdown();
    super.stop();
    LOGGER.info("stopped");
}

However, the program got the error with:

com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for java.util.concurrent.ExecutorService was bound.
 while locating java.util.concurrent.ExecutorService

1 error
at    com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1004)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)

So, how can I get the threadPool instance when application stops.


Solution

  • Named is a binding annotation, so injection key in this case is ExecutorService.class and @Named("name0"):

    injector.getInstance(Key.get(ExecutorService.class, Names.named("name0")))