HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Method to close a lot of closeable objects

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
closeobjectsmethodlotcloseable

Problem

I wrote a method that closes 3 closeable types:

  • java.sql.Connection



  • java.sql.PreparedStatement



  • java.sql.ResultSet



public static void closeAll(final Connection connection, 
                            final PreparedStatement statement, 
                            final ResultSet rs)
         throws SQLException
   {
      try
      {
         if (rs != null)
         {
            rs.close();
         }
      }
      finally
      {
         try
         {
            if (statement != null)
            {
               statement.close();
            }
         }
         finally
         {
            if (connection != null)
            {
               connection.close();
            }
         }
      }
   }


Is there a way to simplify it in Java 6?

In Java 7 I can use an AutoCloseable interface:

public static void closeAll(final AutoCloseable ... closeables)
   {
      if (closeables != null && closeables.length > 0)
      {
         for (final AutoCloseable closeable: closeables)
         {
            try
            {
               closeable.close();
            }
            catch (final Exception ex)
            {
               // log it
            }
         }
      }
   }


Is this a better solution?

Solution

A ResultSet is closed automatically when the Statement that created it is closed.
A Statement is closed automatically when the Connection that created it is closed.

If you want to close everything, just close the Connection.

Context

StackExchange Code Review Q#57182, answer score: 3

Revisions (0)

No revisions yet.