简体   繁体   English

对象引用什么时候会收集垃圾?

[英]When will an object reference get garbage collected?

Someone told me only when a reference be set as null, the garbage collector will collect it. 有人告诉我,只有当引用设置为null时,垃圾收集器才会收集它。 However I think the garbage collector will collect all out of scope references, which have never been set as null. 但是我认为垃圾收集器将收集所有未被设置为null的范围引用。

Anyone can told me when a reference will be claimed by the garbage collector? 任何人都可以告诉我什么时候垃圾收集器会提出索引?

The GC collects objects , not references. GC收集对象 ,而不是引用。

The GC will collect an object some time after it has no more live references. GC将在没有更多实时引用之后的某个时间收集对象。 (the GC is non-deterministic) (GC是非确定性的)

What that someone probably meant was that you can let GC collect an object before it goes out of scope by setting the variable that holds a reference to that object to null . 有人可能意味着你可以让GC在它超出范围之前收集一个对象,方法是将保存对该对象的引用的变量设置为null This technique has been of value in the past for some very rare cases (for example, before a long-running loop that does not reference an object). 对于一些非常罕见的情况(例如,在不引用对象的长时间运行循环之前),此技术在过去一直很有价值。 The compiler technology these days renders this idea virtually useless, because compilers are smart enough to detect these conditions, and act accordingly. 目前,编译器技术使这个想法几乎无用,因为编译器足够聪明地检测这些条件,并采取相应的行动。

GC will removes an object from memory "when it wants". GC将“在需要时”从内存中删除对象。 You can try to run System.gc() but it's just a hint for GC that it should run. 您可以尝试运行System.gc(),但它只是GC应该运行的提示。 Whne GC runs, it finds non-referenced objects (or objects with weak references etc. only). 当GC运行时,它会找到未引用的对象(或仅具有弱引用的对象)。 GC runs frequency depdens on memory space. GC在内存空间上运行频率降低。 It runs most often in eden space. 它最常在伊甸园空间中运行。 By default GC runs in eden space when it gets full, but you can tune up your JVM. 默认情况下,GC在eden空间中运行时会运行,但您可以调整JVM。

Why are you bothering GC in the first place? 你为什么要首先打扰GC? What's your problem? 你怎么了?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM