Versions Compared

Key

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

...

This noncompliant code example opens a file and uses it but fails to explicitly close the file.

Code Block
bgColor#FFcccc

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

...

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.

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
}

...

This compliant solution uses the try-with-resources statement, introduced in Java SE 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
}

...

The problem of resource pool exhaustion is exacerbated 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.

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, rs, 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();
}

...

In this noncompliant code example, the call to rs.close() or the call to stmt.close() might throw a SQLException. Consequently, conn.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();
    }
}

...

This compliant solution ensures that resources are released as required.

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();}
  } catch (SQLException e) {
    // forward to handler
  } finally {
    try {
      if (stmt != null) {stmt.close();}
    } catch (SQLException e) {
      // forward to handler
    } finally {
      try {
        if (conn != null) {conn.close();}
      } catch (SQLException e) {
        // forward to handler
      }
    }
  }
}

...

This compliant solution uses the try-with-resources construct, introduced in Java SE 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
}

...

Some static analysis tools can detect cases where there is leak of a socket resource or leak of a stream representing a file or other system resources.

Related Guidelines

Android Implementation Details

The compliant solution (Java SE 7: try-with-resources) is not yet supported at API level 18 (Android 4.3).

Bibliography

[API 2006]

Class Object

[Goetz 2006b]

 

[J2SE 2011]

The try-with-resources Statement