简体   繁体   English

如果我将对象的所有字段设置为null,它将被垃圾收集器杀死吗?

[英]If I set all fields of an object to null will it be killed from the Garbage Collector?

If, I set all fields of an object to null, it implies that the object is also set to null? 如果将对象的所有字段都设置为null,是否意味着该对象也设置为null? Will it be collected from the Garbage Collector then? 然后会从垃圾收集器收集吗?

No, the Java Garbage collector will only remove objects for which there are no valid references. 不可以,Java垃圾收集器只会删除没有有效引用的对象。

Setting all the fields of an object to null does not reduce the reference count of the object itself. 将对象的所有字段设置为null不会减少对象本身的引用计数。 It may, however, allow the GC to remove the objects that those fields once referenced, if those fields were the only (or last) reference to the objects. 但是,如果这些字段是对对象的唯一(或最后)引用,则可能允许GC删除那些字段曾经被引用过的对象。

The JVM's garbage collector removes the objects where the reference is lost (due to which the program is unable to reach the object). JVM的垃圾回收器除去丢失了引用的对象(由于该原因,程序无法访问该对象)。

If you set the field of an object to null it will not affect the reference. 如果将对象的字段设置为null,则不会影响引用。 So GC would not delete the object. 因此,GC不会删除该对象。

An automatic garbage collector essentially performs two tasks: 自动垃圾收集器实质上执行两项任务:

  1. decide if and when memory needs to be reclaimed 决定是否以及何时需要回收内存

  2. find objects that are no longer needed by the program and reclaim 查找程序不再需要的对象并回收
    their storage 他们的存储

A program has no guarantees that the automatic garbage collector will be run during its execution. 程序无法保证自动垃圾收集器在执行过程中将运行。 A program should not rely on the scheduling of the automatic garbage collector for its behavior 程序的行为不应依赖自动垃圾收集器的调度

know about The Garbage collection 了解垃圾收集

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

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