This is completely wrong with you.
Short answer: finalize() is a tool for cleaning resources (such as open files) just before an object is ready to collect garbage (when no object has a link to it). This may / may not be caused. This is one step ahead of freeing up memory.
Long answer:
There is a separate daemon thread called the finalizer thread, which is responsible for calling the finalize () method. A finalization queue is a queue in which objects are placed that are ready to call the finalize () method.
- When an object is created, the JVM checks to see if the user has overridden the finalize () method. If it is then, it internally notes that this particular object has a finalize () method.
When the object is ready for garbage collection, the garbage collector thread checks if this particular object () is complete from the table specified in (1).
2a) If this is not the case, it is sent to collect garbage.
2b) He has, then he is added to the finalization queue. And it removes the object record from the table (1).
The finalizer continues to track the queue. For each object in the queue, the finalize () method is called. After calling the loop, finalize () from (2) is repeated again. If this object still does not have a strong reference, then it is sent for the GC. If he has then ALWAYS (2a), because the record has been deleted in (2b)
Basically finalize() method is only called once.
So what is the problem with the above loop?
From (1). It will take extra time to create the object. Java memory allocation is 5 to 10 times faster than malloc / calloc, etc. All the time received is lost in the procedure for notifying an object in a table, etc. I tried it once. Create 100,000 objects in a loop and measure the time taken to complete the program in 2 cases: one without finalize (), the second with finalize (). Found it 20% faster.
From (2b): Memory leak and starvation. If an object in the queue has references to many memory resources, then all these objects will not be freed if this object is not ready for the GC. If all objects are objects with a heavy weight, then there may be a shortage.
From (2b): Since finalize () is called only once, what if in finalize () you had a strong reference to the "this" object. The next time the finalie () objects are never called, therefore, it can leave the object in an inconsistent state.
If an exception is thrown inside finalize (), it is ignored.
You do not know when finalize () is called, since you have no control over the GC call. It can sometimes happen that you print the values ββin finalize (), but the output is never displayed because your program could have been completed by the time finalize () was completed.
Therefore, avoid using it. Instead, create a say dispose () method that closes the required resources or the final log, etc.