Is finalizers guaranteed to be called in Java? If it differs from JVM to JVM, what about the case in Dalvik VM for Android?
-
2Too many duplicates to list. Please search first. http://stackoverflow.com/questions/12030641/how-to-ensure-finalize-is-always-called-thinking-in-java-exercise , http://stackoverflow.com/questions/12461995/how-to-properly-implement-a-finalizer-for-detecting-resource-leaks-in-java , http://stackoverflow.com/questions/9540114/why-does-the-finalize-function-not-get-called-in-this-unit-test , http://stackoverflow.com/questions/2954948/performance-implications-of-finalizers-on-jvm (while these are not all exact duplicates, the information needed to answer this post is abundant and found eaily) – Dec 21 '12 at 01:22
-
1While I have linked in questions above, *it would be nice to have a solid answer focusing on the **Dalvik Implementation** of finalizers/GC* which may (or may not) add guarantees above the JLS/JCL and reference JVMs. – Dec 21 '12 at 01:25
-
Dalvik is not a JVM, nor does it want to be. – Jörg W Mittag Dec 21 '12 at 01:53
-
As far as i know, in HostSpot VM finalizers will be called before Objects being GC. – lichengwu Dec 21 '12 at 02:32
3 Answers
No, they are not guaranteed to be called. Do not rely on finalizers to free up resources.
https://www.securecoding.cert.org/confluence/display/java/MET12-J.+Do+not+use+finalizers

- 23,028
- 51
- 143
- 215
Here is an excerpt from a java tutorial Object as a Superclass
The finalize() Method
The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Object's implementation of finalize() does nothing—you can override finalize() to do cleanup, such as freeing resources.
The finalize() method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, if you don't close file descriptors in your code after performing I/O and you expect finalize() to close them for you, you may run out of file descriptors.
The last paragraph is the important one.
Finalizers are just something to be guaranteed to be execute before the instances are going to be reclaimed. I am sure it obeys the same rule on Dalvik VM. Besides that, even the finalizers finally been called, there were executed on unpredicatable point, and in vm specific way, so you'd better just use it as safe net. Before JDK 7 the only way is to export explicit resource releasing method for your class and call them explicitly when want to ensure the resources been released. Try-with-resources can relieve you from the situation with JDK7. Autoclose shou

- 1
- 3