Java garbage collection mechanism:
Java garbage collection is not equivalent to a destructor in C + +. In Java, the space occupied by an object is freed only when the program is on the verge of storage space. So, in a Java program, we usually only consider creating objects, and never care about object cleanup. This strategy is appropriate because the garbage collection itself has a cost, and if you don't use it, you don't have to pay for that part of the cost.
Under what circumstances do we need finalize () :
With garbage collection, we generally do not need to care about object space release, but in some special memory areas, we need to manually clear.
A special memory area is when allocating memory, if an object is processing a non-Java resource, for example, calling the malloc () function like C, allocating storage space, and unless the free () function is called, the storage space will not be freed, resulting in a memory leak. Of course, free () is a function in C and C + +, so you need to call it in Finalize () with a local method, such as a file handle or a window character font, and you want to make sure that the resources are freed before an object is revoked.
Because once the garbage collector is ready to release the storage space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. So we'll write the manual cleanup method in the Finalize () function.
protected void Finalize () {// finalization codehere}
Where the keyword protected is to prevent code that is defined outside the class from accessing the Finalize () identifier.
There are three scenarios in which finalize () is called :
1. All objects are automatically called when garbage collection, such as when running System.GC ().
2. When the program exits, a finalize method is called for each object.
3. Explicitly call the Finalize method
Java Finalize and Garbage Collection