This is a utility class to help manage
SharedResources while configuring a
ContainerBuilder. This
class can still be used without a ContainerBuilder, albeit with the injection APIs (i.e.
#get(Class) and
#get(com.google.inject.Key)) disabled.
The core problem with SharedResources is that they need to be tracked carefully to ensure exception safety in the
code that creates and registers them with a ContainerBuilder. The code for this typically looks like this:
MyServerProvider serverProvider = null;
MyRequestHandler requestHandler = null;
try {
serverProvider = builder.getInstance(MyServerProvider.class);
serverProvider.start();
containerBuilder.serverProviders().install(serverProvider);
requestHandler = builder.getInstance(MyRequestHandler.class);
containerBuilder.serverBindings().bind("http://host/path", requestHandler);
containerActivator.activateContainer(containerBuilder);
} finally {
if (serverProvider != null) {
serverProvider.release();
}
if (requestHandler != null) {
requestHandler.release();
}
}
The ResourcePool helps remove the boiler-plate code used to track the resources from outside the try-finally
block. Using the ResourcePool, the above snippet can be rewritten to the following:
try (ResourcePool resources = new ResourcePool(containerBuilder)) {
ServerProvider serverProvider = resources.get(MyServerProvider.class);
serverProvider.start();
containerBuilder.serverProviders().install(serverProvider);
RequestHandler requestHandler = resources.get(MyRequestHandler.class);
containerBuilder.serverBindings().bind("http://host/path", requestHandler);
containerActivator.activateContainer(containerBuilder);
}
This class is not thread-safe.