At this point, you may have believed that you should use Finalize () as a general purpose cleanup method. What good is it?
The third point to keep in mind is:
Garbage collection is only related to memory!
That is, the only reason the garbage collector exists is to recycle memory that the program no longer uses. So for any activity related to garbage collection, the most notable of these is the Finalize () method, which must also be related to memory and its recycling.
But does this mean that if the object contains other objects, finalize () should explicitly release those objects? The answer is no--the garbage collector is responsible for releasing the memory occupied by all objects, regardless of how the objects were created. It restricts the need for Finalize () to a particular situation. In this case, our object can allocate some storage space in a different way than when the object was created. But you may notice that everything in Java is an object, so what is it all about?
The reason to use Finalize () seems to be that there are times when you need to take a different approach to Java, by allocating memory to do something C-style. This can be done primarily through the "intrinsic approach", which is a way of invoking non-Java methods from Java (the problem with the inherent approach is discussed in Appendix A). C and C + + are the only languages currently supported by intrinsic methods. But because they can invoke subroutines written in other languages, they can invoke anything effectively. Within non-Java code, you might be able to call the malloc () series function of C and use it to allocate storage space. and unless free () is invoked, storage space is not released, causing memory "vulnerabilities" to occur. Of course, free () is a C and C + + function, so we need to call it in an intrinsic method within Finalize ().
After reading the above words, you may have figured out that you don't have to use Finalize () too much. The idea is correct; it is not the ideal place to do ordinary cleanup work. So where should ordinary cleanup work be done?