Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Destructor

 
Jumpy David
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
As there is no destructor in Java , how do I do the clean up I want to do, and don't want to leave to garbage collector.
Thanks,
Jumpy
 
Bindesh Vijayan
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jumpy,
For doing any cleanup, you'll have to depend upon Grabage collector.You will havae to override protected void finalize()throws Throwable from Object class, and define any cleanup that you want to be done when GC is done within this method.Now you will have to call System.gc() from the main,this is a request to the JVM to perform GC.When you send a message to GC it will call the finalize() before performing GCing the object.Remember you need not perform any cleanup when you allocate memory using new operator,GC will manage the cleanup itself as it always runs as a low priority thread behind the program ,it's only when something special is done, you need to perform an extra cleanup.As not doing so will create a bug in your program.This is the standard way of doing it.Of course,you can define any method to do some cleanup and later call it from main,but it is not advisable.
THANKS.

[This message has been edited by Bindesh Vijayan (edited August 30, 2001).]
 
John Bateman
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jumpy David:
Hello,
As there is no destructor in Java , how do I do the clean up I want to do, and don't want to leave to garbage collector.
Thanks,
Jumpy

Be careful, there is NO destructor in Java.
Also, a Finalizer ( obj.finalize() ) is not the equivalent of a destructor.
The reasons are because you can NEVER EVER guarantee that the finalizer will be called.
Even if you 'invoke' garbage colletsion there is no guarantee the jvm will actually clean anything up.
Secondly finalize does not call the finalize from it's inherited classes. (I.E. propogate up the inheritance tree).
So you can not rely on this to clean anything up. You could call "super.finalize()" in each finalize, but, there's also no guarantee in which order they will be executed.
Hope this helps.
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is java. You don't have to worry about memory management. Take a deep breath, ..., relax. Doesn't that feel good?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic