Custom Search

Monday, 20 October 2014

Java Program to illustrate garbage collection ;and how to override that method.


Java Program to illustrate garbage collection, Explain garbage collection giving example in Java language


What is Garbage Collection ?
Whenever memory is allocated using new keyword; a reference is created of the object and required equivalent space is allocated in main memory.Now; when object can not be further used anymore; which means when scope of that object is over; that memory is no more required and is just a kind of digital garbage values. Garbage collector frees this memory. We can override this method explicitly also. Example to override this method is as show below. It will count the milliseconds object was in the scope.

Program
import java.util.Vector;

public class GarbageCollector{
   
    public static void main(String[] args) 
{
    int SIZE = 200;

for (int i = 0; i < SIZE; i++) {
    }
    System.out.println("Garbage Collection started explicitly.");
    long time = System.currentTimeMillis();

System.gc();
System.out.println("It took " + (System.currentTimeMillis()-time) + " ms");
        }
}

No comments:

Post a Comment

Laptops