Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javatutorials garbage collection in java

Related Tutorials


 
 

Share on Google+Share on Google+

garbage collection in java

Advertisement
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.

EXAMPLE

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.gc();
System.out.println("It took " + (System.currentTimeMillis()-time) + " ms");
}
}

Output

C:\unique>javac GarbageCollector.java                  

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

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: Nulling variables and garbage collection,garbage collection java,javatutorial,java tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com