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
FileOutputStreamresource:- 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
@Singletonto the@Providesmethod), then suddenly it's not the responsibility ofClientto close the resource. If oneClientcloses 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
Clientfails (resulting in aProvisionException), then theFileOutputStreamthat may have been constructed leaks and isn't properly closed, even ifClientnormally 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
No comments:
Post a Comment