Many resources in Java need be closed after they have been used. If they are not, the garbage collector cannot reclaim the resources' memory, and
they are still considered to be in use by the operating system. Such resources are considered to be leaked, which can lead to performance issues.
Java 7 introduced the try-with-resources statement, which guarantees that the resource in question will be closed.
try (InputStream input = Files.newInputStream(path)) {
// "input" will be closed after the execution of this block
}
This syntax is safer than the traditional method using try
, catch
, and finally
and hence should be
preferred.
This rule raises an issue if a closeable resources is not opened using a try-with-resources statement.
This rule is automatically disabled when the project’s sonar.java.source
is lower than 7
as the close-with-resources
statement was unavailable prior to Java 7.