Home Java Example Java Io Code for Garbage Collection
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Code for Garbage Collection

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

Code for Garbage Collection

     

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

Description of program:

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 of the program:

C:\unique>javac GarbageCollector.java

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

Download this example.

 

Advertisements

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: March 20, 2008

Related Tutorials

Ask Questions?    Discuss: Code for Garbage Collection   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Javin @ garbage collection in Java
April 16, 2011
garbage collection

I don't think you can force garbage collection in java, you can only request it by calling system.gc() and its upto JVM to run GC.
Santhosh
October 16, 2012
Garbage collection

Thats good but i need something more bro... Where we using GC? What is need for it... Like that
DMCA.com