user1016403
user1016403

Reputation: 12621

Closing opened database connections?

I have two datasources in my web application. i am getting connection as dataSource1.getConnection();.

my question is consider below code:

Connection connection = null;
connection = dataSource1.getConnection();
connection = dataSource2.getConnection();
connection.close();

I am getting dataSource1 connection and immediately assigning dataSource2 connection to connection variable.

As I am closing dataSource2 connection, does dataSource1 connection remains open? Or do I need to do as below?

Connection connection = null;
connection = dataSource1.getConnection();
connection.close();
connection = dataSource2.getConnection();
connection.close();

Upvotes: 2

Views: 160

Answers (3)

Romain
Romain

Reputation: 12829

You need to do as you show in your second code example.

In the first case, the Garbage Collector may clean up the mess for you (after an undefined amount of time) and close the connection that you've lost reference to (provided the JDBC driver vendor implemented the appropriate logic in the finalize method of their Connection implementation), however it is considered extremely bad practice to rely on this to happen.

Upvotes: 1

David R Tribble
David R Tribble

Reputation: 12214

The Connection class implements the AutoClosable interface, which defines "a resource that must be closed when it is no longer needed". So connection objects are defined as needing a call to their close() method in order to be properly managed.

On the other hand, the Connection.close() method is documented as "releasing the Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released". Which implies that somewhere the connection resources will be freed eventually automatically.

On balance, though, I'd say that it's better to explicitly close any connections you no longer need.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236112

The second example is right, the first one will leave an open connection. Also, you should always close resources (connections, in this case) inside a finally block, for example:

Connection connection = null;

try {
    connection = dataSource1.getConnection();
} catch (SQLException e) {
    // handle exception
} finally {
    try {
        connection.close();
    } catch (SQLException e) {
        // handle exception
    }   
}

try {
    connection = dataSource2.getConnection();
    connection.close();
} catch (SQLException e) {
    // handle exception
} finally {
    try {
        connection.close();
    } catch (SQLException e) {
        // handle exception
    }
}

Upvotes: 2

Related Questions