This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I read an article regarding garbage collection in Java. It was advised that it is good practice to tag the connection object to equal to null after it is closed. This somewhat guarantees garbage collection. Is this true?
Originally posted by PINEAPPLE FRUIT: I read an article regarding garbage collection in Java. It was advised that it is good practice to tag the connection object to equal to null after it is closed. This somewhat guarantees garbage collection. Is this true?
Nothing guarantees garbage collection except the programmer who implements it in a particular JVM. You don't want to leave any dangling references though. Whether it is a java.sql.Connection or whatever object, whether or not you set a reference to null may or may not affect garbage collection. If the reference is a method local and there are no other references to the object, then just exiting the method will have the same effect as setting the reference to null. Many programmers mistakenly believe that you can't have a memory leak in Java, but that's not true. Yes, Java has a robust garbage collector, but poor programming techniques can cause forgotten references to linger usually in some sort of Collection. The bottom line is, you have very little to say about how and when the garbage collector reclaims an object, but you have a lot to do with making sure objects become available to be reclaimed. So it certainly doesn't hurt to set a reference to null when you are through with an object, but you need to be sure that no other reference is pointing to the same object in a Collection somewhere.
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher