Is Making the instances as Orphan in finally block requests GC to perform garbage collection on high priority?
No. Assigning null
does not change the "priority" at which objects are garbage collected. Indeed, assuming that the scope for those variables is about to end, assigning null
to them is pointless.
(Assigning null
to some variable or field in Java does not decrement reference counts, etc, and does not trigger the corresponding object to be reclaimed. In fact, the completely GC is oblivious to the assignment event. The most the assignment can do is to make the object unreachable sooner. But in this example where the variable is about to go out of scope, this is going to happen almost immediately anyway. Hence the null
assignment doesn't achieve anything.)
The garbage collection is going to run when the JVM thinks it is the right time, irrespective of what you do. Apart from calling System.gc()
... which is a really bad idea for other reasons!
Under normal circumstances, you shouldn't worry about when the GC runs. However, in this case you are dealing with external resources; i.e. database connections, resultsets and the like. These need to be "managed" properly, or you are liable to run into problems with resource leaks.
If / when the objects do get GC'ed, they will probably be closed by their respective finalize
methods. However, the finialization may well happen too late to avoid the bad consequences of the resource leaks.
So the correct way to manage these is NOT to null
them in the (vain) hope that they will be GC'ed sooner. The correct way to deal with them is to explicitly call their respective close()
methods ... in the finally
block; e.g.
finally {
conn.close(); // This should also close any child Statement and
// ResultSet instances
}
And a better way to do this is to use Java 7 "try with resource" syntax as described by Jon Skeet's answer.