This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assign null to unneeded object

 
Samuel Huang
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

To explicitly assign null to unneeded objects is a good or bad programming habit? Why?
Many thanks in advance!
Samuel Huang
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some people like to do it as they feel that it will be gc quicker. I never do it, it's a style thing.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you have a reference to an object stored in a variable, that object cannot be garbage-collected.
If your reference is in a local variable in a short-duration method, it will go out of scope quickly and be available for garbage collection. Therefore, no need to set reference to null. In this case, setting it to null is a style thing, as the previous posting suggested. I think it's good practice, but can't claim that I actually always do it!
If the variable containing your reference is potentially long-lived (member data of long-lived object or, worse, class static data), then garbage collection could be prevented for a long time or for ever. In such cases, you should set references to null when they are no longer needed, to facilitate garbage collection.
In the worst case, failure to do this can result in a "memory leak".
Extra care has to be taken with arrays and collections. If an array or collection holds a reference to an object, that will prevent garbage collection. Long-lived arrays or collections could therefore cause memory leaks if not used carefully.
 
Samuel Huang
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Christopher and Peter,
Thank you for your opinions, really useful.
Samuel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic