开发者

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 inj开发者_如何转开发ector 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").


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜