Skip to end of metadata
Go to start of metadata

The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the 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 a finalizer to release resources such as Lock or Semaphore objects. This can occur because Java lacks any temporal guarantee of when finalizers 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 finalizers 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 finalizer is called for an object provides a window of vulnerability during which an attacker could induce a denial-of-service (DoS) attack. Consequently, resources other than raw memory must be explicitly freed in nonfinalizer methods because of the unsuitability of using finalizers. See MET12-J. Do not use finalizers for additional reasons to avoid the use of finalizers.

Note that on Windows systems, attempts to delete open files fail silently (see FIO03-J. Remove temporary files before termination for more information).

Noncompliant Code Example (File Handle)

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

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.

Compliant Solution (try-with-resources)

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:

The try-with-resources construct sends any IOException to the catch clause, where it is forwarded to an exception handler. Exceptions generated during the allocation of resources (that is, the creation of the FileInputStream or BufferedReader), as well as any IOException thrown during execution of the while loop and any IOException generated by closing bufRead or stream, are included.

Noncompliant Code Example (SQL Connection)

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:

Noncompliant Code Example

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.

Noncompliant Code Example

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, which violates ERR05-J. Do not let checked exceptions escape from a finally block.

Compliant Solution

This compliant solution ensures that resources are released as required:

Compliant Solution (try-with-resources)

This compliant solution uses the try-with-resources construct, introduced in Java SE 7, to ensure that resources are released as required:

The try-with-resources construct sends any SQLException to the catch clause, where it is forwarded to an exception handler. Exceptions generated during the allocation of resources (that is, the creation of the Connection, Statement, or ResultSet), as well as any SQLException thrown by processResults() and any SQLException generated by closing rs, stmt, or conn are included.

Risk Assessment

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




Remediation Cost









Automated Detection

Although sound automated detection of this vulnerability is not feasible in the general case, many interesting cases can be soundly detected.

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



Parasoft Jtest9.5BD.RES.LEAKS, OPT.CIO, OPT.CCRImplemented
SonarQube Java Plugin3.10S2095Implemented

Related Guidelines

SEI CERT C Coding Standard

FIO22-C. Close files before spawning processes

SEI CERT C++ Coding Standard

FIO51-CPP. Close files when they are no longer needed


CWE-404, Improper Resource Shutdown or Release
CWE-405, Asymmetric Resource Consumption (Amplification)
CWE-459, Incomplete Cleanup
CWE-770, Allocation of Resources without Limits or Throttling

Android Implementation Details

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


[API 2014]

Class Object

[Goetz 2006b]


[J2SE 2011]

The try-with-resources Statement



    • Each code sample should go under a Non-Compliant Code Example section, or a Compliant Solution section. Don't group multiple bad code samples in one section.
    • Your 3rd code section, which closes resources in a 'finally' clause is not valid Java, because the fianlly clause references variables declared in the try clause. You need to declare them outside the try clause for the finally clause to recognize them.
    • Provide a compliant solution for closing the file, which 'fixes' the code in the first noncompliant code.
  1. It is possible to write the compliant code more concisely.

    1. Grazie, I see your point.

  2. I suspect the severity might be medium, in the case that malicious code could access an open file descriptor or database connection and have access to privileged information.

    (This has nothing to do with the grade or assignment, as the assignment is done.)

    1.  In that case, it would a be totally different vulnerability then the one described above. I'm unclear on how an attacker could hijack said unreleased resources - by reflection, perhaps? I'll see if I can get a concrete example of this, do you know of something I can use?

       I would argue that this is more of a DoS attack, since it is highly probable that an attacker can forge multiple calls to a specific function, especially in the case of web based applications, leading to rapid exhaustion of non-memory resources.

       I guess one scenario could be if an attacker manages to exhaust say database connections to the user database, forcing the app to fall back on less secure authentication, maybe an insecure default password file or something. Though that scenario sounds a little more feasible, I'm not sure if it ranks a mention on the page.

      1. It's a DoS problem. In particular it's a problem if the resource can be leaked without allocating significant (Java heap) memory. If the GC doesn't need to run, the finalizers wont be found and eventually will run out. With resource acquisition failing legitimate clients will stop working and therefore probably cause significatly slower allocation of memory, delaying clearing of the problem.

  3. I just thought of a more concise way to write compliant example one:

    In this case, even if rs/stmt are null and an exception is thrown, the rest of the commands are still called. Though it strikes me as bad programming to be so dismissive of generating exceptions easily avoided.

    1. Of course this is very artificial. Real code doesn't go through this for every SQL query. If you did, then I think you'd write a method to encapsulate the sequence.

      In any case, I would write it as:

  4. The intro to this needs to be much clearer in describing what exactly this guideline requires. I think it is confused with specific examples, the descriptions of which should be included in the corresponding noncompliant code examples.

  5. The JDK7 solution is a bit different. It catches exceptions from resource release. "try-with-resource" with catch operates the opposite way around to try with catch with finally. It's unfortunate that the three uses of the try keyword can be mangled into the same structure. A try block with both catch and finally probably has something wrong with it.

    1. I've amended the text for both Java 7 compliant solutions to indicate that the catch clause catches everything, as you suggest. (Also fleshed out other compliant solutions, which weren't fully correct).

      I'm not sure what you mean by 'operates the opposite way', unless you are talking about order of execution. I always assumed order of execution is the same as order of appearance, except that any control-flow statement (return, throw, break, etc) doesn't get executed until all catch and finally clauses are done. If my assumption is wrong, then we probably have fodder for a rule that explains what execution order really is.

      1. What I mean by 'operates the opposite way'.

        Consider this code.

        It is not equivalent to:


        And this is illegal:

        For (rough) equivalence, you need two try blocks (which would be the preferred way of writing it in Java SE 6, although usually the exception handling would be done in a different method).

        1. OK, I see that your 5th code example is the cloesst analogue to how try-with-resources actually works. I modified one of our CS's to use that pattern (embedded try blocks).

          AFAICT there is no functional difference between your 5th code example and your 2nd. The 2nd example is equally correct; it is just a bit bulkier (as the variables are set to null outside the try block). Is there any other reason the 5th code samle is preferred over than the 2nd?

          (BTW all your code samples violate ERR05-J. Do not let checked exceptions escape from a finally block, because the close() can throw, but that's an easy fix.)

  6. Two comments:
    1. In the title, "Release resource..." would be more generic than "Close resource..."
    2. First NCCE: Why "File Handle"? It doesn't look like a Windows specific code example.

    1. 1. Agreed, changed.
      2. Dunno, changed to 'File'.

  7. David,

    In this test case,  I would like to mention one more point.This is related to URLClassLoader. Java 7 has introduced a new method , close()  to close the loader as soon as its operation is over. So this operation closes all opened files and makes eligible for garbage collection. Sample code snippet:

    1. Unni:

      Interesting. I see that URLClassLoader (unlike its parents) implements the Closable interface. This interface requires the close() method, and must be implemented by any class to be used in a try-with-resources clause.

      The URLClassLoader.close() method says:

      In the case of jar: and file: URLs, it also closes any files that were opened by it. If another thread is loading a class when the close method is invoked, then the result of that load is undefined.

      I take this to mean that it closes just the file or socket indicated by the URL, and not any files opened by the class itself.