Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime management with Google Guice

Is there a recommended pattern for shutting down / closing objects created with Guice?

The lifecycle I'm aiming for is:

  1. Prepare a Guice Module
  2. Create an injector
  3. Use the injector through your code to obtain objects (injector.getInstance(Foo.class))
  4. ...
  5. Close any resources held by said objects (file handles, TCP connections, etc...). I want this to be a deterministic step (not "some day when the GC runs").
like image 603
ripper234 Avatar asked Nov 04 '09 14:11

ripper234


1 Answers

I want this to be a deterministic step (not "some day when the GC runs").

Sorry but then Java is the wrong language for you. The DI framework does not know when all the references to an object are gone. Only the GC knows this.

If you have a "closable" resource then use the try/finally pattern to close it (see below).

Closable c = // ...
try {
   c.use();
} finally {
   c.close();
}

Now to back peddle a little. Guice can know when a scope starts and ends. Your custom scope could run a clean up step when it finishes. This scope could even return proxies so the objects would be invalid if you attempted to access them out side of the allowed scope.

(Oh and +1 to ColinD - Inject providers. :)

EDIT: Guiceyfruit seams to have some support for Lifecycles

like image 135
Michael Lloyd Lee mlk Avatar answered Sep 25 '22 00:09

Michael Lloyd Lee mlk