Connecting Tech Pros Worldwide Forums | Help | Site Map

Explicit Nullify and Garbage Collection

dmjpro's Avatar
Lives Here
 
Join Date: Jan 2007
Location: India (West-Bengal)
Posts: 2,451
#1: Jul 7 '09
I read a article few days before. I was thinking to post a question over here..today i got time to post it ;)
Have a look at my codes...

Expand|Select|Wrap|Line Numbers
  1. void testGarbageCollection(){
  2.  String str = "some value .........";
  3.  str = null; //explicit nullify
  4. }
  5.  

Expand|Select|Wrap|Line Numbers
  1. void testGarbageCollection(){
  2.  String str = "some value .........";
  3. }
  4.  
In both code the outside the method the reference str looses reachability. So now it's now ready to collect. But garbage collection request done by JVM only when new memory allocation required or until System.gc is not called. But in my first code str gets nullified inside the method. That means immediately the str is ready to collect, no wait for new memory allocation or System.gc call. Is it true?
Is it good practice? Does it increase the performance of my application?

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Jul 7 '09

re: Explicit Nullify and Garbage Collection


Nullifying doesn't help you much for local variables because, as your wrote already, objects being out of scope can be collected. They won't be collected on the spot, i.e. when you set then to null; the garbage collector decides for itself. As you (might) know already a System.gc() is just a hint to the collector, it still decides when to collect the garbage so in total: there is no use for explicitly nullifying objects in normal circumstances.

Exceptional situations can not be discussed in general because of their peculiar behaviour.

kind regards,

Jos
dmjpro's Avatar
Lives Here
 
Join Date: Jan 2007
Location: India (West-Bengal)
Posts: 2,451
#3: Jul 7 '09

re: Explicit Nullify and Garbage Collection


After reading the link again, i was laughing at myself.
Basically nulling an reference does nothing ;)
Reply