• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can finalize() method execute for an object more than 1 time?

 
Munish Dabra
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i found that
-first by calling System.gc() and suggesting GC to garbage collect th object by allocating some free memory.
-immediate after that i declare the object to be null.
-then print statement in the finalize executed 2 times.Why?
 
vadiraj vd
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Munish,
Could you give the code you tried out?

------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
 
Munish Dabra
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyGC
{
static int num;
MyGC(int n)
{
num=n;
}
public static void main(String ar[])
{
MyGC var1=new MyGC(2);
var1=null;
System.gc();
double array[]=new double[999999]; //Suggestion for gc to run
MyGC var2=new MyGC(1);
var2=null;
System.out.println("Yahoo! i am exiting main()");
}
protected void finalize() throws Throwable
{
System.out.println("i am known as Mr. finalize "+num);
}
}

output:
-------
Yahoo! i am exiting main()
i am known as Mr. finalize 1
i am known as Mr. finalize 1
waht's happening.it is executing finalize for avr2 twice.it just can'nt possible.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NO, it is not executing finalize twice for the same object - it is just that when finalize runs both objects see the same static value for num. GC does not guarantee to run finalize exactly when an object is garbage collected. It can be run later at the JVM's discretion.
Bill

------------------
author of:
 
Zheng Huang
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill is right. If you change "static int num;" to "int num;". You will see the following results.

Yahoo! i am exiting main()
i am known as Mr. finalize 2
i am known as Mr. finalize 1
 
Varsha Dighe
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill,
Are you suggesting that finalize() method on an object can run after the object is garbage collected ?
Any help is appreciated
Varsha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic