This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Total memory: 2031616 Free memory before gc: 1871288 from finalize Free memory after gc: 1914480
if I comment out line1, output is:
Total memory: 2031616 Free memory before gc: 1871304 from finalize Free memory after gc: 1914480
My question is why the Free memory after gc is same in both cases. In first case(without commenting line 1), we have created a new reference which starts referring to same object which is going to be garbage collected so this object should not be eligible for GC.
and if i am wrong then what is meant by: "Calling finalize() can actually result in saving an object from deletion."
In that way the finalize method ties the object being garbage collected to the class variable. The reference from the class variable to the object will now prevent the object from being garbage collected until the class is unloaded. [ September 09, 2006: Message edited by: Barry Gaunt ]
Oh yes, do not expect those free memory numbers to tell the whole truth. Calling the garbage collector may free memory not associated directly with your small program. There are many threads apart from the main thread in the JVM and some memory may be reclaimed from objects discarded from those threads.
Joined: Aug 16, 2006
thanks Barry, I strongly agree what you have suggested but in my changed code when i am referring to the object through instance variable of SuperClass, why the result is not same as i am expecting because as far as i think in this program your code (having static reference) and my later code(having nonstatic reference) should behave in same manner because the scope of nonstatic reference variable ends only when the class gets unloaded.
Joined: Aug 03, 2002
"because the scope of nonstatic reference variable ends only when the class gets unloaded."
No, the lifetime of an instance variable (non-static variable) is the lifetime of the object itself - not the lifetime of the class from which the object is created.
Your object is like a boat being tied to itself - the river can still wash it away. Your instance variable sc is just like a peg on the boat itself.
You have to tie your boat to something firmer - the boat factory perhaps. All boats are made in the boat factory (the class) and something to tie your boat onto would be a peg in that boat factory (a static reference variable). [ September 09, 2006: Message edited by: Barry Gaunt ]