Inheritance and Memory Retention Issue with Finalization
Sunday Jan 13, 2008
Finalization is mostly used in Java to reclaim resources, native
resources. Say, you are writing one program using Windows
Font(OS font). So, its the programmers duty to reclaim the font
resource associated with any object.
If you are an application developer and uses lot of native resource
then I would say stop reading this blog and read the latest Article(yes,
Sep 2007) by Tony Printezis on sun site. This article is awesome and
covers all the cases and its solution that can happen with Memory
Retention. The simplest of that is what I am going to talk here.
Now, consider an example :
class PlayWithFont {
String someText;
String newText;
private native method getFont();
void get() { getFont(); }
// always be called by any method of this class only
private native method releaseFont();
void release() { releaseFont(); }
protected void finalize() { release(); }
}
Now,
here I have some text and I am taking OS font, converting that text
into some fancy text and then releasing the resource of Operating
Systems.
We have a class called PlayMoreWithFont which basically
inherits PlayWithFont and converting some String[] text into new
String[] text (just a fictitious example)
class PlayMoreWithFont {
String[] someMoreText ; // lets consider it here some big chucks of memory
String[] newMoreText;
}
PlayMoreWithFont don't have any finalize method defined, but off course its going to take one from PlayWithFont.
GC maintain a finalization queue. When a object is unreachable, object is
added to the finalization queue. After that only, object goes into
finalized state. Now when we called :
play = new PlayMoreWithFont;
play = null;
Now
instance of PlayMoreWithFont become unreachable, but reclamation of big
chunks like someMoreText and newMoreText has to wait until the instance
is finalized. And this is one of the major causes of memory retention.
Moreover the problem is difficult to find if the class hierarchy is big and finalize is sitting some where very deep.
There are some good solution which we can discuss in next.














