Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();

like image 951
giri Avatar asked Mar 03 '10 18:03

giri


2 Answers

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)

like image 151
Steven Schlansker Avatar answered Sep 28 '22 06:09

Steven Schlansker


We don't.

We just don't.

Perhaps my experience is limited, but I have not once found it necessary to call System.gc().

I will quote Brian Goetz on the performance aspect (if you haven't heard of him, look him up -- and read the rest of this article, too):

A third category where developers often mistakenly think they are helping the garbage collector is the use of System.gc(), which triggers a garbage collection (actually, it merely suggests that this might be a good time for a garbage collection). Unfortunately, System.gc() triggers a full collection, which includes tracing all live objects in the heap and sweeping and compacting the old generation. This can be a lot of work.

In general, it is better to let the system decide when it needs to collect the heap, and whether or not to do a full collection.

like image 36
Michael Myers Avatar answered Sep 28 '22 06:09

Michael Myers