Avoid Injecting Closable Resources · google/guice Wiki · GitHub
There are a number of issues with this approach as it relates to resource management:
- If multiple Client classes are constructed, multiple output streams are opened against the same file, and writes to the file may clash with eachother.
- It's not clear which class has the responsibility of closing the
FileOutputStream
resource:- If the resource is created for the sole ownership of
Client
, then it makes sense for the client to close it. - However, if the resource is scoped (e.g.: you add
@Singleton
to the@Provides
method), then suddenly it's not the responsibility ofClient
to close the resource. If oneClient
closes the stream, then all of the other users of that stream will be dealing with a closed resource. There needs to be some other 'resource manager' object that also gets that stream, and its closing functions are call in the right place. That can be tricky to do correctly.
- If the resource is created for the sole ownership of
- If, for example, the construction of the other dependencies of
Client
fails (resulting in aProvisionException
), then theFileOutputStream
that may have been constructed leaks and isn't properly closed, even ifClient
normally closes its resources correctly.
The preferred solution is to not inject closable resources, but instead, objects that can expose short-lived closable resources that are used as necessary. The following example uses Guava's CharSource as the resource manager object:
Read full article from Avoid Injecting Closable Resources · google/guice Wiki · GitHub