Hello. I have a PreparedStatement/CallableStatement, a ResultSet and a Connection...

Now after execution finishes, i want to release my resources.


First I close my connection...
I also want to release my ResultSet and my PS

Will assigning null to my Connection object after closing the Connection object also assign null to my PS and ResultSet.

Do I need to assign null to my PS and RS.

myConnection.close();
myConnection = null;
myConnection.close();
myConnection = null;
myResultSet = null;
myPreparedStatement = null;

What is the difference between these two ?

Which is best for performance?

Does assigning null value to a connection also assigns null to PS and RS?

Will assigning null to the connection trigger the garbage collector?

Is code 2 better than code 1 when it comes releasing the resources?

Thanks...

To understand this you need to be clear about the difference between an object and a reference variable.
myConnection and myResultSet are not objects, they are reference variables. Either they hold a reference to an object of the appropriate type, or their value is null.
There is no way you can make an object equal to null. Objects are created by the "new" statement, and continue to exist until there are no references left to them. So when you say myConnection = null, you are making the variable myConnection not refer to the connection object anymore. This does not trigger garbage collection, which happens whenever the garbage collecter choses according to its own very complex rules.
Whether that causes the object to garbage collected or not dependes on whether there are any other active references to it anywhere in your code OR in the Java API objects that you have created/used.
So what youi need to do is to ensure that every variable you have that refers to these objects (or refers to another object that has a reference to them) either goes out of scope or is set to null. You will no longer have anyway to access these objects, and some time later ther garbage collecter will garbage collect them.
In general, worrying too much about garbage collection in Java is a waste of time; trying to optimise it doubly so.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.