views:

453

answers:

1

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").
+1  A: 

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

mlk
I think this is just a classic misunderstanding of what the GC is for (particularly easy to make this mistake if you've programmed in C++). In a garbage collected language, object lifetime/GC has nothing to do with releasing resources like file handles or network sockets.
Simon Howard
The code block doesn't allocate the object, so it is not responsible for releasing it. Specifically singletons (within a Guice module) are obtained by Injector.getInstance(), but should not be closed after used.
ripper234
This whole issue depends a lot on exactly what you're doing and in what context. Different objects have different lifecycles, different scopes, etc. so there is no catch-all easy solution. Are you doing this in a webapp? Are you mainly talking about closing singletons on shutdown?
ColinD
Singletons can only be "released" during the application shutdown (so via a shutdown hook). I'm sure you could write a scope that handled that.
mlk
Also, if a code block retrieves a no-scoped object from a provider and uses it, it would definitely be responsible for closing that object if necessary despite not creating it itself.
ColinD
The code block doesn't allocate the object - Is the object created via a provider (or injected Injector) or injected into that object. If it is provided I would say that class that requested it is responsible for releasing it.
mlk
http://code.google.com/p/google-guice/issues/detail?id=62
mlk