对象何时有资格进行垃圾收集?

When Is The Object Eligible For Garbage Collection?(对象何时有资格进行垃圾收集?)
本文介绍了对象何时有资格进行垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,假设 amethod 已被调用.myObject 最初引用的对象在哪一点/哪一行符合垃圾回收条件?

In the code below, given that amethod has been called. At what point/line is the Object originally referenced by myObject, eligible for Garbage Collection?

class Test {
  private Object classObject;

  public void amethod() {
    Object myObject = new Object();
    classObject = myObject;
    myObject = null;
  }
}

如果 classObjectamethod 具有 public、protected、default 或 static 的访问修饰符,它会影响对象符合垃圾收集条件的点吗?如果有,会受到怎样的影响?

And if classObject or amethod had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?

  • 我的第一个想法是,当 Test 对象符合垃圾回收条件时,该对象符合垃圾回收条件.
  • 但话又说回来了.优化器可能知道 classObject 永远不会被读取,在这种情况下 classObject = myObject; 将被优化出来并且 myObject = null; 是它有资格进行垃圾收集的点.
  • My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection.
  • But then again. The optimizer may know that the classObject is never read from in which case classObject = myObject; would be optimized out and myObject = null; is the point it is eligible for Garbage Collection.

推荐答案

对象将不会成为垃圾回收的候选对象,直到对它的所有引用都被丢弃.Java 对象是通过引用分配的,所以当你有

The object will not become a candidate for garbage collection until all references to it are discarded. Java objects are assigned by reference so when you had

   classObject = myObject;

您为堆上的同一对象分配了另一个引用.所以这一行

You assigned another reference to the same object on the heap. So this line

   myObject = null;

只去掉一个引用.要使 myObject 成为垃圾回收的候选对象,您必须拥有

Only gets rid of one reference. To make myObject a candidate for garbage collection, you have to have

  classObject = null;

这篇关于对象何时有资格进行垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)