Firstly,The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected.
For example, Closing an opened database connection.
The finailze()
method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.
About What is the best chances when GC will called finalize() method?, There are two ways in which we can request the JVM to execute the Garbage Collection:
Runtime.getRuntime().gc();
System.gc();
What type of resources we can close in finalize(), the answer is in two situation:
Set all availabel object references to null
after the purpose of
creating the object is done.
Make the reference variable to refer to another object: Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Grabage Collection.