• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

finalize() method doubt

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

As far as i know, the finalize() method is called before the object is destroyed by the automatic garbage collector.

My doubt is, if an object is not reachable then will it immediately execute the finalize() method?

If so, then why the below code is not printing the message in finalize() method after line //2 is executed.


public class GarbageCollect
{
String id;

GarbageCollect(String objid)
{
id = objid;
}

public static void main(String[] args)
{
GarbageCollect obj1 = new GarbageCollect("one"); //line 1
obj1 = new GarbageCollect("two"); //line 2
}

protected void finalize() throws Throwable
{
System.out.println(id + "Garbage Collected");
super.finalize();
}
}

Please correct me if my understanding is wrong.

Thanks in advance!!
Regards,
Surekha.
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Objects wont be GC-ed immediately they are eligible for Garbage collection. You can suggest JVM to garbage collect by calling System.gc();

Try the below code.
 
We can walk to school together. And we can both read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic