Avoiding Resource Leaks

Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.

The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy. E.g., the following snippet represents an obvious resource leak:

    int len(File f) throws IOException {
        InputStream stream = new FileInputStream(f);
        return stream.available();
    }

The compiler will flag this with "Resource leak: 'stream' is never closed".

Basic Flow Analysis for Resource Leaks

Flow analysis detects the following situations:

Additionally, flow analysis tries to follow resource values through variable assignments. However, if different resources may be assigned to the same variable (on different control flows or in sequence), the analysis can become less accurate.

Not all the analysis is enabled by default. Please consult the compiler preferences regarding the individual configuration options.

Hints: Code will generally be easier to analyze (and easier to understand by human readers) if resource-type variables are not reused for different purposes. Ideally, in Java 7 programs all resources should be managed with a try-with-resources statement.

Ownership / Responsibility

The above diagnostics basically assume that a method that creates an instance of a resource type is also responsible for closing this resource. However, some resources will be shared among several methods. Here the analysis makes the following assumptions:

Resource Wrappers and Resource-free Closeables

The JDK defines a few classes which implement Closeable but do not directly represent a resource at the level of the operating system.

java.io.StringReader is an example of a closeable that doesn't require calling close() because no operating system resources are held that would require clean-up. The analysis uses an explicit white list to detect classes from java.io that fall in this category. No resource leak warnings are issued regarding these classes.

Instances of classes like java.io.BufferedInputStream are wrappers around another resource (where wrappers can be applied at multiple levels). Also these objects do not directly represent an operating system resource. If the wrapped resource is closed, the wrapper doesn't need closing. Conversely, if a wrapper is closed this will include closing of the wrapped resource. The analysis has a second white list for detecting wrapper resources, and will recognize whether the underlying actual resource will be closed directly or indirectly via the wrapper. Either one suffices to silence warnings regarding resource leaks. The white list contains classes from java.io, java.util.zip, java.security, java.beans and java.sound.sampled.

Hint: It is generally preferable/safest to close the outermost wrapper, not a wrapped resource.