Is there a recommended pattern for shutting down / closing objects created with Guice?
The lifecycle I'm aiming for is:
- Prepare a Guice Module
- Create an injector
- Use the inj开发者_如何转开发ector through your code to obtain objects (
injector.getInstance(Foo.class)
) - ...
- 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").
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
精彩评论