regarding garbage collection.Why do we need to call System.gc();?

garbage-collection, java

Solution

You don't. As you say, garbage collection is automatic. System.gc() doesn't even force a garbage collection; it's simply a hint to the JVM that "now may be a good time to clean up a bit"

In general, trying to force the garbage collector to do what you want with System.gc() is a hack applied by people who think they know better than they actually do, or as an (attempted) workaround for broken code.

I've been writing Java for years and I've yet to see a situation where calling System.gc was really the right thing to do (in anything I've written)

Problem

Garbage collection is called automatically when an object is refered to is no longer available to any variable. But I like know why do we call explicitly using System.gc() when garbage collection is called automatically.When do we call System.gc();

Original source