Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - System.gc() for garbage collection

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...