{{blog.title}}
{{blog.date}} | {{blog.stars}} stars
Author: Kiran
• Thursday, September 13, 2007

Modern programming languages and their environments include Automatic Memory Management. For sure, the development community loves this cool feature; for it simply means that you can allocate as much memory as you want and then completely forget about releasing it!.

It is not just about the convenience, but has more – it helps programmers become more productive. Because, it allows them to concentrate better on the problem at hand, without having to keep track of the number of bytes they allocated and ensure that it is released. If they forget, well, tough luck, the memory just got leaked. Such bugs not only eat up memory and slow down the system, they are really hard to debug. It might eat up a few weeks in your schedule, if any such thing were to happen in a complex multi-threaded application, with a one thread allocation memory and a different one releasing it.

In case of managed environments like Java, the Garbage Collector 'frees' up memory that is no longer required i.e., there are no variables referring to the object’s memory – it can be reclaimed. The Java specification does provide a hook that allows us to 'resurrect' the objects that are about to be trashed.

According to the Java specification the object’s finalize() method is to be invoked, before reclaiming the object’s memory. The trick is to hoodwink the garbage collector by adding a reference to the object in the finalize() method. The following piece of code illustrates it:

import java.util.ArrayList;
public class Resurrect
{
private Resurrect anchor = null;
private String name = "";
private static ArrayList list = new ArrayList();

public Resurrect(String name)
{
super();
this.name = name;
}
public void finalize()
{
System.out.println(name + ": Finalize");
anchor = this;
// Add the object to the 'resurrection' list
list.add(this);
}
public void printMessage()
{
System.out.println(name + ": Am alive!!!");
}
private static void printList()
{
// Print all the 'resurrected' objects
for (int i = 0; i < list.size(); i++)
{
System.out.print(i + ": ");
Resurrect r = (Resurrect) list.get(i);
r.printMessage();
r.anchor.printMessage();
}
}
public static void main(String[] args)
{
Resurrect r1 = new Resurrect("r1");
Resurrect r2 = new Resurrect("r2");
// Deliberately switch r1 to refer r2, leaking r1.
r1 = r2;

// Explicitly invoke the Garbage Collector.
System.gc();
try
{
// Print the messages through both references
r1.printMessage();
r2.printMessage();
}
finally
{
try
{
/*
* Sleep to ensure that the current
* thread won't finish ahead of the
* Garbage Collector thread.
*/
Thread.sleep(5000);
}
catch (Exception e)
{
}
printList();
}
}
}

This entry was posted on Thursday, September 13, 2007 and is filed under , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response , or trackback from your own site.

0 comments :