All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.squid.S2095.html Maven / Gradle / Ivy

There is a newer version: 8.6.0.37351
Show newest version

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. Failure to do so will result in a resource leak which could bring first the application and then perhaps the box it's on to their knees.

Noncompliant Code Example

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.
}

Compliant Solution

OutputStream stream = null;
try{
  stream = new FileOutputStream("myfile.txt");
  for (String property : propertyList) {
    // ...
  }
}catch(Exception e){
  // ...
}finally{
  stream.close();
}

Exceptions

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 ( ... ) {
  //...
}

See





© 2015 - 2025 Weber Informatics LLC | Privacy Policy