Is there a recommended pattern for shutting down / closing objects created with Guice?
The lifecycle I'm aiming for is:
injector.getInstance(Foo.class)
)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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With