V6127. Closeable object is not closed. This may lead to a resource leak.
The analyzer has detected that an object implementing the Closeable
interface is not closed for all execution paths.
The Closeable
interface indicates that the object holds data (resources) that can be closed, such as files or open connections.
If the reference to the object that holds the resource is lost, the resource will not be closed. This can lead to memory leaks, OS resource leaks, or other negative consequences.
In this example, the file remains open after use:
public void objectIsNotClosed(File f) {
try {
FileInputStream fis = new FileInputStream(f); // <=
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
// Exception handling
}
}
The object is not closed within the try
block, so the file stream cannot be closed once the block is exited.
To prevent a file descriptor leak, call the close
method on the file stream object:
public void objectIsClosedInFinally(File f) {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
// Exception handling
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Exception handling
}
}
}
}
Java 7 has introduced a more concise and convenient way to manage resources—try-with-resources
. You can read more about it in the documentation.
Please note that Oracle recommends using try-with-resources
instead of the previous method of closing resources.
The example with try-with-resources
:
public void objectIsClosed(File f) {
try (FileInputStream fis = new FileInputStream(f)){
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
// Exception handling
}
}
This diagnostic rule also highlights cases when the Closeable
object is created within a constructor that may throw an exception. This implementation is unsafe because if an exception is thrown, the Closeable
object will be created, but its reference will be lost and remain open.
This diagnostic is classified as: