Wednesday, February 8, 2012

CloseUtils: closing resources silently

When working with resources in Java it is important that they are closed after use. Usually it is done by calling close() method in finally block. The problem is that close() method can throw an Exception. The following class allows you to close resources silently, so you save some try-catch lines.

Resources, since Java 1.5, implement java.io.Closeable interface:

interface Closeable {
   public void close() throws IOException;
}

So you can make a method, that would close any Closeable resource.

public class CloseUtils {
   private static final Logger logger = Logger.getLogger(CloseUtils.class);

       public static void close(java.io.Closeable closeable) {
         if (closeable != null) {
            try {
                closeable.close();
            } catch (java.io.IOException e) {
                logger.error("Error closing resourse/stream ", e);
            }
         }
      }
}

So, instead of having finally block like this:

InputStream is = ...
try{
...
} finally {
   if (is != null) {
      try {
            is.close()
      } catch (IOException e) {
            logger.error(e);
      }
   }
}

you can use the following code

InputStream is = ...
try {
...
} finally {
   CloseUtils.close(is);
}

P.S. Java 7 comes with a new construction called "try with resources" that automatically closes the resources that were declared in try block. See: The try-with-resources Statement


No comments:

Post a Comment