Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My code is:

class Test{
    Test c=new Text();
    System.out.println(c.size());
    System.gc();
}

Can programmer use System.gc() for garbage collection in java? Is it preferrable? JVM performs automatically, then why should programmer to call System.gc()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
199 views
Welcome To Ask or Share your Answers For Others

1 Answer

System.gc() sends a request to the GC to perform a collection cycle. This request may be served or it may be ignored, therefore neither result should be relied on.

A garbage collection cycle will happen automatically (without any action on your part), usually when the generation responsible for allocation of new objects is full or an allocation request cannot be satisfied at all.

In most cases, you should not need to call System.gc() at all in your code. System.gc() should be used in a few cases in which conditions similar to the following apply:

  • You know that a large amount of memory has just become unreachable.
  • It is essential that this amount of memory be freed quickly.
    • Or your program is about to enter a time-critical state where a GC cycle should happen as late as possible (or not at all) and so it helps to perform a GC cycle before you enter that state.
  • You have at least a rough idea of how the GC of the target environment works.
  • You have verified that the strategy of that GC is not optimal for your scenario at that point.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...