What triggers garbage collection [duplicate]

↘锁芯ラ 提交于 2021-01-27 18:27:40

问题


I know what all gets garbage collected. But what exactly tells JRE that it is time for garbage collection? Is it like some event or time interval?


回答1:


HotSpot's garbage collection has grown into an exceedingly complex business, which even its creators struggle to understand in full detail. Therefore you can't be given a simple answer; some triggers are:

  1. occupation of each object generation reaching a threshold;
  2. a memory allocation request in a specific generation failing;
  3. overall heap occupation reaching a threshold.

Note that you haven't even specified what kind of garbage collection you are interested in: there is a minor collection and a major collection, and technologically they are very different. You have also not specified which Garbage Collector you have in mind: HotSpot has four of them to choose from.

If you are a beginner with Java, the best advice to give is a) in day-to-day programming, don't worry about it; and b) if you want to learn, you'll have to dig deep.




回答2:


object has null reference then it will garbage collected. but GC does not give guarantee like when it is done.




回答3:


I thing as a good practices dont fully depend on GC,See THIS OR THIS




回答4:


The JVM controls the Garbage collector, it decides when to run the Garbage Collector. It will run the GC when it realizes that the memory is running low or an object become eligible for GC when no live thread can access it.

But this behavior of JVM cannot be guaranteed, one can request the GC to happen from within the java program but there is no guarantee that this request will be taken care by JVM.




回答5:


Garbage collection in java happen when JVM thinks it needs a garbage collection based on Java heap size.

But you can force GC to collect garbage using

System.gc () 

or

Runtime.gc () 

But it’s not guaranteed that garbage collection will happen.

Read more: http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz2Y9gKzQE1




回答6:


You can use System.gc(); but there's no guarantee that it'll run (it just "suggests" to the GC to run).

The JVM has different implementations, including the GC which can be run in different modes, and has very complex algorithms which usually work pretty good, that said, if you have a special usage (or special events, like after a restart of a platform) - you can tune it using flags (like: minimum heap size, maximum heap size and etc), but even without doing so, the GC collects objects that have null reference (pointers that points to them) whenever there's a need to free memory from the heap.



来源:https://stackoverflow.com/questions/17483415/what-triggers-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!