•
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
{
{
public Resurrect(String name)
{
super();
this.name = 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);
}
{
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!!!");
}
{
System.out.println(name + ": Am alive!!!");
}
{
// 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();
}
}
r.anchor.printMessage();
}
}
{
Resurrect r1 = new Resurrect("r1");
Resurrect r2 = new Resurrect("r2");
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)
{
}
{
// 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();
}
}
}
}
}
}
Programming
,
Technical
|
0 comments :