0

Its just a foolish queation from a java programmer. I have something like

PreparedStatement stmt = DBConnection.getConnection()
                .prepareStatement(sql);

Now in finally block I check if stmt exists and then close it. What will happen to Connection object in this case. I know if I write in separate lines then I can close it as I have a reference to connection object which I don't have in this case.

0

2 Answers 2

3

What will happen to Connection object in this case.

Nothing. There is no magic, so the connection isn't magically closed, just because you didn't assign it to a variable.

That's why you use a separate variable for the Connection: so you can call close()! Or use try-with-resources:

try (Connection connection = DBConnection.getConnection()) {
    PreparedStatement stmt = connection.prepareStatement(sql);
}
Sign up to request clarification or add additional context in comments.

Comments

-1

The connection will remain open until it is garbage collected at some time in the future.

However, in the case of connection pools, yours might not be the only reference to the Connection (if the pool also maintains a reference to connections which have been borrowed). In this case garbage collection will not take place, and the collection will not be closed. It will have "leaked" from the pool, which will likely eventually cause the pool to be exhausted and no further connections will be available.

5 Comments

No, GC will not close open connections for you. That's why the close() method exists.
@MattBall I suppose it is up to the jdbc driver implementation. Connections /should/ be closed in finalize if not closed explicitly. This is not a recommendation to rely on garbage collection to close connections. They absolutely should be closed in a finally block. This is similar to InputStreams and other resources.
You cannot safely rely on finalize alone. And what about connection pooling? The point is that the code must somehow explicitly tell the system when it's done with the connection/stream/resource.
@MattBall Even with connection pooling gc could work if the connection pool hands out a proxy or wrapper that wraps the physical connection (which BTW is the usual implementation) and does not keep a strong reference to this proxy.
@MattBall Again, I am simply stating what /will/ happen, which was the question, not one /should/ do. I added some additional detail around the potential impact of pooling further delaying or preventing GC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.