garbage collection in java

garbage collection



Garbage Collection in Java

In java, objects are dynamically allocated using new() keyword. But the key question is what happened to these objects when they have no use. How these objects are destroyed for later reallocation of their memory. In java this is done automatically through garbage collection. In other words it deallocate memory automatically which have no longer use. This technique is known as Garbage Collection.

In this way, java ensures that sufficient memory will available to your program. It (Garbage Collection) is controlled by the configuration parameters of the heap.

Note: Heap resides in the physical memory which is incorporated by the Java Virtual Machine(JVM) for the creation of  objects. The configuration parameter of the heap are Xms & Xmx. You can use these configuration parameter as :

java ?Xms:256m Xmx:1g

It points that the Xms(minimum heap size) is 256Mb & Xmx(Maximum heap size) is !024Mb.


In this section, you will learn how to force a garbage collector to work by creating many objects.

The following code of program will help you in forcing the garbage collection. First of all we have created an object for the garbage collector to perform some operation. Then we have used the System.gc(); method to force the garbage collection on that object. Then we have used the System.currentTimeMillis(); method to show the time take by the garbage collector.

import java.util.Vector;

public class GarbageCollector{
public static void main(String[] args) {
int SIZE = 200;
StringBuffer s;
for (int i = 0; i < SIZE; i++) {
System.out.println("Garbage Collection started explicitly.");
long time = System.currentTimeMillis();
System.out.println("It took " + (System.currentTimeMillis()-time) + " ms");



C:\unique>java GarbageCollector
Garbage Collection started explicitly.
It took 782 ms