Monday, October 3, 2011

Detecting resource leaks with Eclipse JDT

You can now detect resource leaks with Eclipse JDT. The following 3 warnings have been added, and the defaults are as shown (this feature is available in I-Builds starting Oct 4 )

For the purpose of this analysis, a resource is a local variable of type in pre-Java 7 world and in Java 7 world a resource is a local variable of type java.lang.AutoCloseable. (Note that in Java 7 extends java.lang.AutoCloseable)

To take a few examples

  • if close() is never called on the resource a 'Resource is never closed' warning is emitted

  • if close() is called but not on all code paths, the warning indicates the locations where the resource is not closed

  •  if a locally created resource is passed to another method, then it cannot be ascertained what that method does with the resource, i.e. the method may or may not close the resource, e.g. in the snippet below a helper method is used to close a resource, however one may also create helper methods to perform other tasks. Hence, in these cases the warning is a 'Potential resource leak' and this warning is not enabled by default.

  •  if a resource is correctly closed, and the compiler compliance is 1.7 then Eclipse suggests to use the new try-with-resource statement

Several other cases are also handled, e.g. a resource is returned from a method, a resource variable is reassigned etc. However, we may have missed something, hence bugs, suggestions and comments are welcome!

Most of the credit for this feature goes to Stephan Herrmann, in fact I often wonder how he gets time to contribute so much to JDT given that he has a day job and is also the lead of the Eclipse Object Teams Project. Thanks Stephan!