March 16, 2021

Garbage Collection

        As we all know that java programming language is robust and had so many features available and also adding features versions by versions. Like garbage collection, it supports this feature from the very early versions of the java.

        What garbage collection do is it destroys the unnecessary resources from the memory. This is the thing which java does automatically, which we can not see with the help of programming.

          But still this feature is very much helpful when we are creating very large scale applications or some scientific applications. We can not control the way it destroys the resources from the memory, but what we can do is simply force the compiler to free the resources. First we need to understand that this process is completely automatic, by forcing the compiler to free the resources means that we are giving instructions to the system that this the resource which we don't want to use it can free the resource from the system.

        This is not necessary to implement garbage collection in each and every program or application of the java , as it is part of the automatic process, but in the large scale applications it is in constant need to free memory at some point so at that time we can force the system to free the unnecessary resources for the smoothness of the application.

    To implement the garbage collection we need to call a built in method "System.gc()", and implement finalize() method  in your class. Here below is the simple example of Garbage collection.


class MyTest{

static int cnt = 0;

MyTest() {

System.out.println(cnt + " Object is Created");

        }

{//Simple block for increment of the counter when object is created in memory

cnt++;

}

static void showCnt(){

System.out.println("Total objects are created : " + cnt);

}

protected void finalize() {

System.out.println("Object Destroyed : " + cnt);

cnt--;

}

}

class MyClass{

public static void main(String[] a) {

MyTest t = new MyTest();

for(int i =0 ;i < 5 ; i++)

new MyTest();

MyTest.showCnt();

System.gc();

MyTest.showCnt();

}

protected void finalize() {

System.out.println("MyClass Destroyed");

}

}


        Type the above example save it as any name you want and run the MyClass when you run the above program you every time you will see different output .Below is the screenshot of the output I had when I had run the same program. 




No comments:

Post a Comment