gpt4 book ai didi

java - 当一个对象被取消引用但它的成员对象仍然被引用时会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:24 25 4
gpt4 key购买 nike

class ClassA {
ClassB mem1 = new ClassB();
ClassB mem2 = new ClassB();
}

class ClassB {
}

public class Sample {
public static void main(String[] args) {
ClassA obj1 = new ClassA();
ClassB obj2 = obj1.mem1;

obj1 = null;

obj2 = null;
}
}

在上面的程序中,行:obj1 = null之后发生了什么?

即使仍在引用 obj1 的成员对象之一,是否已准备好进行垃圾回收?

最佳答案

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

Java Garbage Collection Basics

在此上下文中,当处理 obj1 = null; 时,没有对其指向的 ClassA 类型的对象的引用,因此它符合垃圾回收的条件。然而,ClassB 对象 mem1 仍然具有 obj2 形式的引用,因此至少会保留到执行 obj2 = null; 行。

关于java - 当一个对象被取消引用但它的成员对象仍然被引用时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com