Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the Java garbage collector cannot free nonmemory resources such as open file descriptors and database connections. Consequently, failing to release such resources can lead to resource exhaustion attacks. In addition, programs can experience resource starvation while waiting for finalize() to release resources such as Lock or Semaphore objects. This can occur because Java lacks any temporal guarantee of when finalize() methods execute, other than "sometime before program termination." Finally, output streams may cache object references; such cached objects are not garbage-collected until after the output stream is closed. Consequently, output streams should be closed promptly after use.

A program may leak resources when it relies on finalize() to release system resources or when there is confusion over which part of the program is responsible for releasing system resources. In a busy system, the delay before the finalize() method is called for an object provides a window of vulnerability during which an attacker could induce a DoS attack. Consequently, resources other than raw memory must be explicitly freed in nonfinalizer methods because of the unsuitability of using finalizers. See the rule MET12-J. Do not use finalizers for additional reasons to avoid the use of finalizers.

Note that on the Windows platformsystems, attempts to delete open files fail silently. See rule FIO03-J. Remove temporary files before termination for more information.

...

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 created in the first place).

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

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

...

The try-with-resources construct sends any IOException to the catch clause, where it is 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 execution of the while loop. Finally, it includes any IOException generated by closing bufRead or stream.

...

Code Block
bgColor#FFcccc
public void getResults(String sqlQuery) {
  try {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sqlQuery);
    processResults(rs);
    stmt.close(); conn.close()
  } catch (SQLException e) { /* forward to handler */ }
}

...

This noncompliant code example attempts to address exhaustion of database connections by adding cleanup code in a finally block. However, either or both of rs and , stmt, or conn could be null, causing the code in the finally block to throw a NullPointerException.

Code Block
bgColor#FFcccc
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 {
  rs.close();
  stmt.close(); conn.close();
}

Noncompliant Code Example

In this noncompliant code example, the call to rs.close() or the call to stmt.close() might throw a SQLException. Consequently, stmtconn.close() is never called. This is a violation of rule ERR05-J. Do not let checked exceptions escape from a finally block.

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

Compliant Solution

This compliant solution ensures 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
}

The try-with-resources construct sends any SQLException to the catch clause, where it gets is 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.

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="aec12dcc20f48c30-92a63fff-46a04df1-832fab1f-eac6759d4927aad22ee7913b"><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="e9d24d0787977abf-60b057b1-49fb41d0-b1be920e-06e293dee7b3f974fd5e2b74"><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="990ebcba537f4913-6dc17c79-47fa4f4c-988a9758-60020227a90492e5fe23404f"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]]

The try-with-resources Statement

]]></ac:plain-text-body></ac:structured-macro>

...