...
Resources other than raw memory must be explicitly freed in non-finalizer methods, due to the unsuitability of using finalizers.
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it, but fails to explicitly close the file handle.
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName) throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
|
Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, the FileInputStream
object is closed as required (if it was created in the first place).
Code Block | ||
---|---|---|
| ||
FileInputStream stream = null;
BufferedReader bufRead = null;
try {
stream = new FileInputStream(fileName);
bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// forward to handler
}
}
}
|
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resources statement, introduced in Java 1.7, to release all acquired resources, regardless of any exceptions that might occur.
Code Block | ||
---|---|---|
| ||
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
}
|
The try-with-resource construct will send any IOException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
. It also includes any IOException
thrown during the while loop. Finally, it includes any IOException
generated by closing bufRead
or stream
.
Noncompliant Code Example (SQL Connection)
The problem of resource pool exhaustion is aggravated in the case of database connections. Many database servers allow only a fixed number of connections, depending on configuration and licensing. Consequently, failure to release database connections can result in rapid exhaustion of available connections. This noncompliant code example fails to close the connection when an error occurs during execution of the SQL statement or during processing of the results.
...
In this noncompliant code example, the call to rs.close()
could throw an SQLException
; consequently, stmt.close()
would never be called. This is a violation of ERR05-J. Do not let checked exceptions escape from a finally block.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } |
Compliant Solution
This compliant solution ensures that resources are released as required.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { // forward to handler } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // forward to handler } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { // forward to handler } } } } } } |
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resource construct, introduced in Java 1.7, to ensure that resources are released as required.
...
The try-with-resource construct will send any SQLException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the Connection
, Statement
, or ResultSet
. It also includes any SQLException
thrown by processResults()
. Finally, it includes any SQLException
generated by closing rs
, stmt
, or conn
.
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it, but fails to explicitly close the file handle.
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName) throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
|
Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, the FileInputStream
object is closed as required (if it was created in the first place).
Code Block | ||
---|---|---|
| ||
FileInputStream stream = null;
BufferedReader bufRead = null;
try {
stream = new FileInputStream(fileName);
bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// forward to handler
}
}
}
|
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resources statement, introduced in Java 1.7, to release all acquired resources, regardless of any exceptions that might occur.
Code Block | ||
---|---|---|
| ||
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
}
|
The try-with-resource construct will send any IOException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
. It also includes any IOException
thrown during the while loop. Finally, it includes any IOException
generated by closing bufRead
or stream
.
Risk Assessment
Failure to explicitly release non-memory system resources when they are no longer needed can result in resource exhaustion.
...
FIO42-C. Ensure files are properly closed when they are no longer needed | |||||
FIO42-CPP. Ensure files are properly closed when they are no longer needed | |||||
| CWE-404 "Improper Resource Shutdown or Release" | ||||
| CWE-459 "Incomplete Cleanup" | ||||
| CWE-770 "Allocation of Resources Without Limits or Throttling" | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2e668243487a3348-4afb15ce-4f1648df-a3ea8caf-df93980153cc0ce8f4015f26"><ac:plain-text-body><![CDATA[ | [[MITRE 2009 | AA. Bibliography#MITRE 09]] | [CWE-405 | http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)" | ]]></ac:plain-text-body></ac:structured-macro> |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0194e9b83dcf5731-38f4cc71-4c9a48cc-b6b385e4-294d1a7fc39eb11d7018870a"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | [Class Object | http://java.sun.com/javase/6/docs/api/java/lang/Object.html] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5da2eb89b61e34eb-86e77bff-464147bd-91fc906b-cd3da28e996fc97832b12280"><ac:plain-text-body><![CDATA[ | [[Goetz 2006b | AA. Bibliography#Goetz 06b]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="11612838e734226c-3281e8f8-46e348e7-854c8b9a-8eec6ef57d74fd39a2dd6719"><ac:plain-text-body><![CDATA[ | [[J2SE 2011 | AA. Bibliography#J2SE 11]] | The try-with-resources Statement | ]]></ac:plain-text-body></ac:structured-macro> |
...