gpt4 book ai didi

java - 如果一个对象只有一个实例变量可访问,垃圾收集器会做什么

转载 作者:行者123 更新时间:2023-12-02 08:58:12 24 4
gpt4 key购买 nike

我的问题是这段代码片段中的注释所说的内容:

public class A {
int x = 0;
}

public class B {
String text = "a";
A a = new A();
}

public class Test {
public static void main(String[] args) {
A a = null;
if (a == null) {
B b = new B();
a = b.a;
}
// what happens with b inside the if statement now?
// does a still point to b's instance variable?
// what does the garbage collector do in this case?
}
}

因为 B 类拥有另一个名为 text 的实例变量,我想知道垃圾收集器在这种情况下会做什么。 if 语句内的 if b 不会被垃圾回收,并且 a 仍然指向 b 的实例变量 a >,那么text不会浪费内存空间吗?

编辑:

主函数内部的

a 稍后会以某种方式使用,并且并非无法访问!

有趣的部分是 b 发生的情况,因为 B 内的 a 仍然被引用,但 text不是。

最佳答案

public static void main(String[] args) {
A a = null;
if (a == null) {
B b = new B();
a = b.a;
}
// let's suppose GC is called here
}

ab 实例在 if 语句之后都不使用 - 如果 GC 运行,它们可以并且将会被回收,两者他们。您可以将“未使用”理解为“无法访问”。它是如此简单。

另一方面,如果将其更改为:

public static void main(String[] args) {
A a = null;
if (a == null) {
B b = new B();
a = b.a;
}
// GC called here
// somehow use "a"
}

如果您使 a 可访问,则它无法被回收,只有 b 可以,因为,好吧 - 没有人需要它。

关于java - 如果一个对象只有一个实例变量可访问,垃圾收集器会做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60363501/

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