Garbage collection mechanism - finalize()

Java provides the finalize () method. When the garbage collector is ready to release the memory, it will call finalize() first . 

The reason to use finalize() is that there are special cases that the garbage collector cannot handle . Suppose your object (not using the new method) acquires a "special" memory area, since the garbage collector only knows about the memory space that was explicitly allocated via new , so it doesn't know how to free this "special" memory area, then at this time java allows to define a finalize() method in the class.

This situation mainly occurs in native methods. For example, native methods call the C/C++ method malloc() function series to allocate storage space , but unless the free() function is called, these memory spaces will not be released, then at this time may cause memory leaks. But since the free() method is a function in C/C++ , it can be called by a native method in finalize(). to free up these "special" memory spaces.

The main is to release some memory space opened up by other practices , and to do some cleanup work .

Finalize process: When the object becomes unreachable (GC Roots), the GC will determine whether the object has covered the finalize method, and if not, it will be recycled directly. Otherwise, if the object has not executed the finalize method, it is put into the F-Queue queue, and a low-priority thread executes the finalize method of the object in the queue. After the finalize method is executed, the GC will again determine whether the object is reachable. If it is not reachable, it will be recycled. Otherwise, the object will be "resurrected".


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324801784&siteId=291194637
Recommended