• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is it good practice to nullify strings and objects after use to minimize chances of out of memory.

 
Monica Shiralkar
Ranch Hand
Posts: 866
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it good practice to nullify strings and objects after use to minimize chances of out of memory. By nullifying string I am talking about below code:



Should this be done after the last use of objects?

thanks
 
C Sanders
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
People apparently smarter than I have said that it's not necessary to set local scope variables to null because the compiler is smart enough to figure out when they are not needed anymore.
However, if there are member variables that will remain longer than they are needed, it is a good idea to set them to null in order to help prevent memory leaks.
 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's good practice to declare variables in the tightest possible scope. Once they go out of scope the objects they refer to are eligible for garbage collection, and you have nothing to gain by explicitly setting them to null.

That said, there are certain Java classes that attach native resources. If you create() a Graphics object, it's good practice to dispose() it when no longer needed. Under certain circumstances, it may be desirable or even necessary to flush() an Image. A top level Swing or AWT window can be dispose()d to release native resources. Various Listeners may still be reachable long after they are needed; you don't need to set them to null but you may need to removeXxxListener(...) to make them eligible for GC.

And of course streams and database connections should always be properly closed.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it is not good practice and not necessary to do this all the time.

Only do this when you have a really good reason to do so. In real code, this is almost never necessary.
 
Maneesh Godbole
Saloon Keeper
Posts: 11196
15
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And never ever ever have a "helper" method which will accept an object instance and set it to null
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic