There is currently no such facility in the standard Java toolchain.
In addition to the Eclipse compiler warnings (see New Idiot's answer), some static code analysers can warn you about this:
- For PMD, the
CloseResourcedesign rule covers this (or at least some subcases ...)
- FindBugs can also do this; e.g. FindBugs - "may fail to close stream" when using ObjectOutputStream
But the problem is these warnings are more or less heuristic. They only understand certain standard idioms for reliably closing resources. If you do it some other way (which is still provably reliable) they are likely to produce a false warning. This is not necessarily bad (because doing this a non-standard way is liable to fool / puzzle future readers!). However the possibility of false positives may tempt developers to ignore or (worse still) suppress the warnings.
There are a couple of additional issues:
These checks may give a false negative for resource objects that have a
close()method without implementing
These checks may give a false negative for
AutoCloseableresource objects where the
close()operation is a no-op; for example,
These issues may explain why the standard Java toolchain doesn't support this.
blog comments powered by Disqus