有多少对象符合垃圾收集器的条件?
How many objects are eligible for the garbage collector?
能否请您查看我对问题的解决方案:"How many objects are eligible for the garbage collector on the line (// custom code)?"
class Dog {
String name;
}
public class TestGarbage {
public static void main(String[] args) {
Dog d1 = new Dog();
Dog d2 = new Dog();
Dog d3 = new Dog();
d1 = d3; // line 1
d3 = d2; // line 2
d2 = null; // line 3
// custom code
}
}
我从文档中了解到:"The object will not become a candidate for garbage collection until all references to it are discarded."
对象和引用:(其中 A、B 和 C 是创建的对象)
d1 -> A
d2 -> B
d3 -> C
------- d1 = d3 ------
d1 -> C
d2 -> B
d3 -> C
------- d3 = d2 ------
d1 -> C
d2 -> B
d3 -> B
------- d2 = null ------
d1 -> C
d2 -> null
d3 -> B
A 符合删除条件,所以我们可以说只有一个对象符合垃圾收集器的条件!
这种做法对吗?
你是对的,只有 A
,创建的第一个 Dog
对象,显然可以收集。
但是,如果您的 "custom code" 不包含对 d1
、d2
或 d3
的任何引用,则这些变量可以随时被编译器将所有 Dog
个对象保留为 GC 候选对象。
能否请您查看我对问题的解决方案:"How many objects are eligible for the garbage collector on the line (// custom code)?"
class Dog {
String name;
}
public class TestGarbage {
public static void main(String[] args) {
Dog d1 = new Dog();
Dog d2 = new Dog();
Dog d3 = new Dog();
d1 = d3; // line 1
d3 = d2; // line 2
d2 = null; // line 3
// custom code
}
}
我从文档中了解到:"The object will not become a candidate for garbage collection until all references to it are discarded."
对象和引用:(其中 A、B 和 C 是创建的对象)
d1 -> A
d2 -> B
d3 -> C
------- d1 = d3 ------
d1 -> C
d2 -> B
d3 -> C
------- d3 = d2 ------
d1 -> C
d2 -> B
d3 -> B
------- d2 = null ------
d1 -> C
d2 -> null
d3 -> B
A 符合删除条件,所以我们可以说只有一个对象符合垃圾收集器的条件!
这种做法对吗?
你是对的,只有 A
,创建的第一个 Dog
对象,显然可以收集。
但是,如果您的 "custom code" 不包含对 d1
、d2
或 d3
的任何引用,则这些变量可以随时被编译器将所有 Dog
个对象保留为 GC 候选对象。