Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added Java 1.7 try-with-resources CSs

...

Code Block
bgColor#ccccff
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 {
  try {
    if (rs != null) {
      rs.close();
    }
  } finally {
    try {
      if (stmt != null) {
        stmt.close();
      }
    } finally {
      conn.close();
    }
  }
}

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.

Code Block
bgColor#ccccff

try (Connection conn = getConnection();
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(sqlQuery)) {

    processResults(rs);
} catch (SQLException e) { 
  // forward to handler 
}

Noncompliant Code Example (File Handle)

...

Code Block
bgColor#ccccff
FileInputStream stream = null;
BufferedReader bufRead = null;
String line;
try {
  stream = new FileInputStream(fileName);
  bufRead = new BufferedReader(new InputStreamReader(stream));

  while ((line = bufRead.readLine()) != null) {
    sendLine(line);
  }
} catch (IOException e) { 
  // forward to handler 
} finally {
  if (stream != null) { 
    stream.close();
  } 
}

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
bgColor#ccccff

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 
}

Risk Assessment

Failure to explicitly release non-memory system resources when they are no longer needed can result in resource exhaustion.

...

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] [Class Object| http://java.sun.com/javase/6/docs/api/java/lang/Object.html]
\[[Goetz 2006b|AA. Bibliography#Goetz 06b]\]
\[[J2SE 2011|AA. Bibliography#J2SE 11]\] The try-with-resources Statement
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE-405|http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)", [CWE-404|http://cwe.mitre.org/data/definitions/404.html] "Improper Resource Shutdown or Release", [CWE-459 |http://cwe.mitre.org/data/definitions/459.html] "Incomplete Cleanup," [CWE-770|http://cwe.mitre.org/data/definitions/770.html], "Allocation of Resources Without Limits or Throttling"

...