org.sonar.l10n.java.rules.squid.S2095.html Maven / Gradle / Ivy
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
- MITRE, CWE-459 - Incomplete Cleanup
- CERT, FIO04-J - Release resources when they are no longer needed
© 2015 - 2025 Weber Informatics LLC | Privacy Policy