제대로 닫지 않은 resource 가 있는 code 검출하기
개요
방법
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
CloseResource
design 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 implementingCloseable
orAutoCloseable
.These checks may give a false negative for
Closeable
/AutoCloseable
resource objects where theclose()
operation is a no-op; for example,StringWriter
.
These issues may explain why the standard Java toolchain doesn't support this.