Garbage Collector Program in JAVA

  • 0
Java language dynamically allocates the memory to the objects of the classes being used in the program. Unlike C++ where a destructor is needed to free the memory, JAVA employs Garbage Collector Mechanism to reclaim the allocated memory. When no referance to the object exists in the memory, it becomes eligible to be collected by Garbage Collector. The finalize method provided by java sees to it that this method is executed just before the memory allocated to the object is being reclaimed. There is no gurantee that a finalize method would be executed. My aim was to observe the functioning of the garbage collector. So, I created a program. And here it is.
package ClassIllustration;

class GarbageCollectorTest
{
    public static void main(String args[])
    {
        int i;
        GarbageCollectorTest[] gct = new GarbageCollectorTest[100000];

        for(i=0;i<100000;i++)
        {
            gct[i] = new GarbageCollectorTest();
            gct[i].print();
            gct[i] = null;

        }
    }

    void print()
    {
        System.out.println("An Instance Method is called here.");
    }

    protected void finalize()
    {
        System.out.println("I am being flushed");
    }
}
It is obvious that it would exceed the memory buffer of the terminal or command prompt whichever you are using. So,
javac -d . GarbageCollectorTest.java
and
java  ClassIllustration.GarbageCollectorTest > File
The whole output of the execution would be piped to file named "File". And with any text editor, you can see the contents of the file.

No comments:

Post a Comment