Why execution of finalize()
isn't guaranteed at all in Java? Is finalize()
method shouldn't be used???
Consider below program.
class Test{
protected void finalize()
{
System.out.println("Will i execute?");
}
public static void main(String args[])
{
Test t=new Test();
}
}
There is an empty output when this program runs. We know that finalize()
is used to cleanup any external resources before the object becomes eligible for garbage collection & finalize()
will be called by JVM. Inside finalize()
we will specify those actions that must be performed before an object is destroyed. Is finalize()
method evil??
18 Answers. Save this answer. Show activity on this post. The finalize method is called when an object is about to get garbage collected.
“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.
Method SummaryDeprecated. The finalization mechanism is inherently problematic. Finalization can lead to performance issues, deadlocks, and hangs.
Why is the finalize() method's access modifier is made as protected. Why cant it be public? It is not public because it shouldn't be invoked by anyone other than the JVM. However, it must be protected so that it can be overridden by subclasses who need to define behavior for it.
Javadoc link, because many quotes will follow.
We know that finalize() is used to cleanup any external resources before the object becomes eligible for garbage collection
No. Once the object becomes eligible for garbage collection, then finalize()
can get invoked. finalize
could theoretically make the object no longer eligible for garbage collection and the garbage collector would then skip it. As stated
After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died
Why execution of finalize() isn't guaranteed at all in Java?
It is guaranteed to run. As the Javadoc states
The general contract of finalize is that it is invoked if and when the Java™ virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized.
What isn't guaranteed is when or if garbage collection will occur.
Should i use finalize() or not in java?
That depends on your use case. Start by reading the javadoc and understand the implications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With