Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a destructor for Java?

Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect?

To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed.

Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed.

I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.

like image 295
wai Avatar asked Oct 05 '08 13:10

wai


People also ask

Why is there no destructor in Java?

Java has its own garbage collection implementation so it does not require any destructor like C++ . This makes Java developer lazy in implementing memory management. Still we can have destructor along with garbage collector where developer can free resources and which can save garbage collector's work.

What is a destructor in Java?

Destructors in Java can be learned with the finalize method in Java. The concept is as same as the finalize method. Java works for all except the destructor with the help of the Garbage collection. Therefore, if there is a need for calling the destructor, it can be done with the help of the finalize method.

How do you destruct a class in Java?

class KillMe { .... public void destroy() { this. getObject = null //this is only for demonstrate my idea } .... } Why would you want to? Anyway, java objects cannot be "destroyed" by anything other than the garbage collector.


1 Answers

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

like image 189
Garth Gilmour Avatar answered Sep 22 '22 18:09

Garth Gilmour