Search code examples
javajava-6

Closing resources in Java


I'm currently doing something like this in java to free resources. Do I need to call close on the BufferedWriter object or is it called in the destructor? With regard to Resource1 and Resource2, I must call release and free respectfully. Is this the correct approach with nested trys? Python has a really nice "with statement" which associates resources with a code scope. Does java have the likes?

Resource1 r1 = new Resource1();
try
{
    ...
    Resource2 r1 = new Resource2();
    try
    {
        ...
        java.io.BufferedWriter f = new java.io.BufferedWriter(new java.io.FileWriter(new java.io.File("f")));
        try
        {
           ...
        }
        finally
        {
           f.close(); 
        }
    }
    finally
    {
        r2.release(); 
    }
}
finally
{
    r1.free(); 
}

UPDATE: I'm using Java 1.6


Solution

  • What you have with respect to BufferedWriter is correct.

    However, you may want to swallow any exceptions that occur during close. This is annoying but necessary. Often the following pattern is used:

    BufferedWriter f = null;
    try {
      f = new BufferedWriter(...);
      ...
    }
    finally {
      try {
        if(f != null) {
          f.close();
        }
      }
      catch(IOException e) {
        // Nothing can be done, except maybe log it.
      }
    }
    

    IOUtils.finallyClose() can be used to remove the need for the catch on close.

    Java doesn't quite have the concept of destructors, but it does have finalize() that get's call when an object is garbage collected. You should never depend on finialize() to close or otherwise cleanup an object.

    Btw, Java 7 introduced a shorter syntax for closing objects that implement Closeable.

    try (BufferedWriter f = new BufferedWriter(new FileWriter(new File("f"))) {
      ...
    }
    

    EDIT: I expanded on finally..close.