Core Java Interview Questions and Answers
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:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- What are the differences between the methods sleep() and wait()?