Is is a good practice to set JDBC object references to null after closing them?
Consider following scenario:
1. There is a class A which contains an instance variable(con) of type Connection and a getConnection and setConnection method. The getConnection method initializes a connection using JNDI lookup.
Suppose there is a class B which subclasses class A. There is a method in class B which uses con (Instance Variable inherited from class A ). con is initialized by calling getConnection (inherited method from class A.).
The question is whether we should set the reference con to null (con=null) after finishing up all jdbc tasks and calling con.close(). Is there a thing like closedConnection instance which is still referred by variable con untill con is set to null.
Yes, the Java object representing the closed connection is still there until the reference is gone.
It might ultimately depend on the JDBC driver and/or connection pool implementation you're using, but I'd say any memory overhead of that is not going to be very big. So unless you're keeping many thousands of closed connections around, you don't have to worry. If you want to be absolutely sure, take a heap dump of your application and analyse it to see how much memory is occupied by these dead connections. This might be useful to you, you might be surprised when you find out where the important chunks of memory actually went.
Joined: Aug 19, 2010
Thanks for the inputs.
In the application I am working on, the number of sessions rise to 3000-4000 at times. So the number of connections created are significant.
In the scenario that I mentioned in my previous post, if we have reference variables in method local scope(rather than global one) then after the connection is closed and method execution is complete then the closedConnection objects will automatically become eligible for garbage collection, right?
Yes, if the connection is referenced by a local variable, or is part of an object referenced by a local variable, then it becomes eligible for garbage collection as soon as that variable goes out of scope.
If you kept closed connections in some kind of global structure and didn't free them, then they might cause problems with memory over time. It would be a classical memory leak actually; the fact that the objects contributing to the leak are closed connections would be unimportant. You'd have to find and solve it using the same techniques as any other memory leak.
Joined: Aug 19, 2010
Thank you .
I will now proceed with heap analysis to see if closedConnection count in memory in my application is significant.
Closing this thread.
subject: Setting connection,resultset=null after closing them