Garbage Collection

In the example we are describing how the garbage collector works.

Garbage Collection

In the example we are describing how the garbage collector works.

Garbage Collection

Garbage Collection

     

In the example we are describing how the garbage collector works.

Description of program: 

In the example given below, first we are creating three objects to give the garbage collector something to do, then we are assigning some values to these variables and then appending values to the StringBuffer variable strbuf and setting the null values to these objects so that they can be garbage collected. Now we are taking the system's current time in milliseconds into a long type variable then calling the garbage collector method gc() of the System class and then system's current time after the garbage collection operation completes and subtracts the previous time from the last one to determine the time taken by the garbage collector to complete its operation and prints this time on the console.


Here is the code of this program:
 

import java.util.Vector;

public class GarbageCollection {  
  public static void main(String[] args) {

  int size = 5000;
  StringBuffer strbuf;
  Vector vctr;
  
  for (int i = 0; i < size; i++) {
  strbuf = new StringBuffer(70);
  vctr = new Vector(50);
  strbuf.append(i).append(i+1).append(i+2).append(i+3);
  }

  strbuf= null;
  vctr = null;
  System.out.println("Staring explicit Garbage Collection.");
  long time = System.currentTimeMillis();
  System.gc();

  System.out.println("Garbage Collection took " + 
  (System.currentTimeMillis()-time) + " ms");

  int[] arr = new int[size*10];
  // null out the variable so that the array can be garbage collected
  time = System.currentTimeMillis();
  arr = null;
  System.out.println("Staring explicit Garbage Collection.");
  System.gc();

  System.out.println("Garbage Collection took " + 
    (System.currentTimeMillis()-time) + " ms");  
  }
}


Here is the output:

C:\Examples>java GarbageCollection
Staring explicit Garbage Collection.
Garbage Collection took 984 ms
Staring explicit Garbage Collection.
Garbage Collection took 16 ms


Download of this program.