• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is it a good idea to Call finalize() method from my code.

 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it a good idea to call MY overrided finalize method when i think I no more needed that Object referrence?
Of course, i can write another method which clean up resources, insted of calling finalize ...but i am curious and not seen any code ..which calls finalize explicitly.
Thanks
Bhagya
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MOSTLY finalize() is used for classes which get deep and dirty with the operating system. If you look at Sun's source code you will find lots of uses of it.
For instance if you look at the source for AWTEvent it has:


Or for java.io.FileInputStream

Since most of the stuff that the average programmer writes is much higher level than that, there is less need. Look particularly for any JNI calls that you have that might not clean up after themselves.
 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! that's true..it does lot of good stuff.What i actually meant is for example,i have two calsses here which are defined in different Packages.I am calling fainalize method Of A from Class B.IS this advisable?
Package a;

Class A {

public void finalize(){
//MY code to clean UP
}
}

Package b;
class B{
void clenUp(){
A handlerA=new Handler();
handlerA.finalzie();
}
}
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NOOOOOOOO!!!
YOU don't call finalize() the garbage collector does that!!
Before the storage for an object is reclaimed by the garbage collector, the Java virtual machine will invoke the finalizer of that object.
Finalizers provide a chance to free up resources that cannot be freed automatically by an automatic storage manager. In such situations, simply reclaiming the memory used by an object would not guarantee that the resources it held would be reclaimed.

I hate to do this to you but you might want to look over the Java Language Specification:
JLS 12.6.1 Implementing Finalization
[ November 11, 2002: Message edited by: Cindy Glass ]
 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...I guessed so.Now i am clear with your Answer that i must not call finalize method.
Any more sussestions and their views are welcome on this topic.
[ November 11, 2002: Message edited by: kumar B ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic