aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can finalize() method execute for an object more than 1 time? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can finalize() method execute for an object more than 1 time?" Watch "can finalize() method execute for an object more than 1 time?" New topic
Author

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

Munish Dabra
Greenhorn

Joined: Jan 07, 2001
Posts: 7
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

Joined: Dec 15, 2000
Posts: 68
Hi Munish,
Could you give the code you tried out?

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

*****************
There's a lot of I in J.
*****************


Regards<BR>---------<BR>vadiraj<P><BR>*****************<BR>There's a lot of I in J.<BR>*****************
Munish Dabra
Greenhorn

Joined: Jan 07, 2001
Posts: 7
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

Joined: Mar 22, 2000
Posts: 12788
    
    5
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

Joined: Dec 20, 2000
Posts: 49
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

Joined: Oct 14, 2000
Posts: 32
Bill,
Are you suggesting that finalize() method on an object can run after the object is garbage collected ?
Any help is appreciated
Varsha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can finalize() method execute for an object more than 1 time?