aspose file tools
The moose likes Beginning Java and the fly likes Destructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Destructor" Watch "Destructor" New topic


Jumpy David

Joined: Jan 17, 2001
Posts: 10
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.
Bindesh Vijayan
Ranch Hand

Joined: Aug 21, 2001
Posts: 104
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.

[This message has been edited by Bindesh Vijayan (edited August 30, 2001).]
John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
Originally posted by Jumpy David:
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.

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.

SOURCE CODE should be SURROUNDED by "code" tags.
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

This is java. You don't have to worry about memory management. Take a deep breath, ..., relax. Doesn't that feel good?

Please ignore post, I have no idea what I am talking about.
I agree. Here's the link:
subject: Destructor
It's not a secret anymore!