I recently came across some feedback on some code that I wrote that mentioned I had issues with connection leaks. From what I understand, a connection leak is when you don't close a connection after you have opened it. Is this correct?
An pseudo - code example of what I was doing that caused this feedback to occur is something like the following:
DbUtils - a class that handles the closing of a connection.
DatabaseInfo = a class that holds connection data.
The methods loadSomeData and loadSomeMoreData are private methods that simply open statements and result sets, then close them in a finally block. They then throw any exceptions that occur.
I understand this is a bit abstract, and I will write up a more detailed example if need be. Thanks guys.
In this pseudo-code Connection is declared as local inside try-catch block, and it is not visible in catch and finally blocks,
so this code cannot compile.
If this code compiles fine - it means that you close some other connection in finally block.
Adding to the previous post, I would highly recommend you set your Connection objects to null. If you are using any sort of Connection Pooling, setting the Connection object to null returns the connection back to the Connection Pool so it can be reused. It also marks that specific Connection object as ready for garbage collection. Also, I would catch a SQLException and perhaps log the exception.
When a Context instance is done with a connection (closed or garbage collected), the connection is returned to the pool for future use.
the Java community typically uses close() to return connections.
I would advise you to do the same. When you call close(), the connection is immediately returned to the pool. That is predictable behavior. Can you predict how/when/if the garbage collector handles it?)