Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core%20Java%20Interview%20Questions%20and%20Answers

Question: How can you force garbage collection?
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

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");
	}
}
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook