Java's garbage collection cannot be relied on to clean up everything. Specifically, connections, streams, files and other classes that implement
the Closeable interface or it's super-interface, AutoCloseable, must be manually closed after creation. Further, that
close call must be made in a finally block, otherwise an exception could keep the call from being made.
Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box it's on to their knees.
private void readTheFile() throws IOException {
Path path = Paths.get(this.fileName);
BufferedReader reader = Files.newBufferedReader(path, this.charset)) {
// ...
reader.close(); // Noncompliant
}
private void doSomething() {
OutputStream stream = null;
try{
for (String property : propertyList) {
stream = new FileOutputStream("myfile.txt"); // Noncompliant
// ...
}
}catch(Exception e){
// ...
}finally{
stream.close(); // Multiple streams were opened. Only the last is closed.
}
}
private void readTheFile() throws IOException {
Path path = Paths.get(this.fileName);
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(path, this.charset)) {
// ...
} finally {
if (reader != null) {
reader.close();
}
}
}
private void doSomething() {
OutputStream stream = null;
try{
stream = new FileOutputStream("myfile.txt");
for (String property : propertyList) {
// ...
}
}catch(Exception e){
// ...
}finally{
stream.close();
}
}
Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resources
statement are ignored by this rule.
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
//...
}
catch ( ... ) {
//...
}