Java Recap: finalize() Method and Garbage Collector

Overview

I highlight several important facts about Java data cleanup of finalize method and the garbage collector, your program logic should not rely on them.

Important facts about finalize method and garbage collector

One of the common “unsafe” programming is that we forget to clean up or free memory, Java try to address this issue by introducing the garbage collector mechanism, however, does garbage collector really free programmers from the cleanup work? The following are some details and important facts I think we need to keep in our mind when using Java.

  1. Neither garbage collection nor finalization is guaranteed. If the JVM is not lose to running out memory, then it might not wast time recovering memory through garbage collection.  That is, do not rely on finalize() being called.

  2. The garbage collector only knows how to release memory allocated with the keyword new. It indicates that for those memory allocated by using say malloc(), there is nothing garbage collector could do.

  3. finalize() is different from destructor, because object is not destroyed immediately after the object is not used. it works like this: when the garbage collector is ready to release the storage used for your object, it will first call finalize(), and only on the next garbage-collection pass will it reclaim the objects’s memory. So finalize() gives us the ability to perform some important clean up at the time of garbage collection, (note it is quite different from destructor which is called when an object is destroyed).

  4. Remember the following facts!

  • Your objects might not get garbage collected!
  • Garbage collection is not destruction! Because you have no idea when the object would be garbage collected, finalize() will be called only when the object is garbage collected, so do not count on finalize() by treating it as destructor, if you want to do some cleaning work like immediately clean up some image on the screen, do it explicitly rather than do it in finalize() which you have no control when the image would be cleaned up.
  • Garbage collection is only about memory. This indicate finalize() method must able be only about memory and its deallocation.
  1. finalize() is in place when you do something by allocating memory using a mechanism other than the normal on in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. C and C++ are the only languages currently supported by native methods, and since C and C++ can call other languages, you can effectively call any language actually.

Summary

In this post, I highlighted several important facts about Java data cleanup of finalize method and the garbage collector, your program logic should not rely on them. Please feel free to share your comments about them.

Written on December 5, 2014