This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Does Java have destructors at all?

Does Java have destructors at all? I couldn’t find any documentation about finding a. If not, how can I achieve the same effect?

To make my problem more specific, I wrote an application that processed the data and explained that there was a reset button that would restore the application to its original state. But all data must be alive unless the application is shut down or the reset button is pressed.

As a C/C++ programmer, I think this is easy to implement (so I plan to implement it later). I structure my program so that all objects that can be reset are in the same class, so that I can destroy all surviving objects when the reset button is pressed.

I wonder if I would have a memory leak if I just unreferenced them and waited for the garbage collector to collect them. If I input data too often and hit the reset button. Unconsciously, Java is already a very mature language, and there might be a way to prevent this from happening or gracefully handle it.

answer

Because Java is a language with garbage collection, you can’t predict when an object will be collected. Therefore, there is no direct equivalent destructor.

There is an inheritance method called Finalize, but its call is completely determined by the garbage collector. Therefore, it is necessary to specify the classes that need to be cleaned up. The convention is to define them ina closing method and use finalize methods only for completeness check. (If the close method is not called, finalize is executed immediately and the error is written to the log)

A recent issue has led to an in-depth discussion of Finalize. If you want to go deeper, you can go to Finalize

The article translated from Stack Overflow:stackoverflow.com/questions/1…