Tuesday, 3 June 2014

How to Explicitly Invoke Garbage Collection in Java

This is a common interview question asked to assess a candidate's understanding of Java Garbage Collection.

Answer: A programmer can request garbage collection by calling System.gc() or Runtime.getRuntime().gc().

However, you should be very careful when using System.gc(). Calling this method only requests that the JVM perform garbage collection—it does not guarantee that garbage collection will occur immediately. Unnecessary calls to System.gc() can negatively impact your application's performance.

In general, you should avoid calling System.gc() explicitly in your application. The JVM automatically manages memory and decides the most appropriate time to perform garbage collection.

For more details, click the link When does System.gc() do something?

No comments:

Post a Comment