Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java garbage collection

Java automatically calls garbage collector, then why we need manual calls for garbage collection? When should use System.gc()

like image 398
Nageswaran Avatar asked Feb 23 '11 03:02

Nageswaran


People also ask

What triggers Java garbage collection?

Common triggers for garbage collection are Eden space being full, not enough free space to allocate an object, external resources like System. gc(), tools like jmap or not enough free space to create an object.

When exactly JVM runs garbage collector?

When the JVM doesn't have necessary memory space to run, the garbage collector will run and delete unnecessary objects to free up memory. Unnecessary objects are the objects which have no other references (address) pointing to them.

How does JVM garbage collection work?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

Does Java support garbage collection?

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM.


1 Answers

Java automatically calls garbage collector, then why we need manual calls for garbage collection?

We don't need them. Indeed, in most circumstances calling System.gc() is harmful for application performance. See my answer to "Why is it a bad practice to call system gc" for a detailed explanation.

When should use System.gc()

If the application knows it is going into a phase where it has nothing else to do AND the user is unlikely to notice a garbage collection, then maybe it is OK call to System.gc() in an effort to stop the user experiencing GC pauses in the future.

The downsides include:

  • Calling System.gc() typically triggers a full GC which takes significantly longer than a GC of the 'new space'.
  • The user may actually care / notice. For example, if you call System.gc() between "levels" in a game, you make loading the next level take longer.
  • By forcing the GC, you are causing the JVM to use extra CPU cycles, etc which may potentially interfere with other things that the user is doing on his machine.

(There can also be legitimate reasons to call System.gc() in unit tests, and during system debugging.)

like image 176
Stephen C Avatar answered Sep 21 '22 13:09

Stephen C