我被问到一个问题(在这个网站http://scjptest.com/ ):有多少对象有资格在此代码示例中的代码示例中进行垃圾回收// //一些代码在这里?
class A { private B b; public A() { this.b = new B(this); } } class B { private A a; public B(A a) { this.a = a; } } public class Test { public static void main(String args[]) { A aa = new A(); aa = null; // some code goes here } }正确的答案是:“由a和b引用的对象有资格进行垃圾回收。” 但为什么? 它们包含彼此的循环引用,它们可以彼此访问。
谢谢!
I was asked a question (on this site http://scjptest.com/): How many objects are eligible for garbage collection in this code sample at the line // some code goes here?
class A { private B b; public A() { this.b = new B(this); } } class B { private A a; public B(A a) { this.a = a; } } public class Test { public static void main(String args[]) { A aa = new A(); aa = null; // some code goes here } }The correct answer is: "The objects referenced by a and b are eligible for garbage collection.". But why? they contain loop references to each other, they are accessible to each other.
Thank you!
最满意答案
它们包含彼此的循环引用,它们可以彼此访问。
是的,但他们无法从其他地方访问,因此无法在程序中看到并使用它们。
早期的GC在收集这种自引用对象组时遇到了问题,但是对于现代世代收集器而言,这是一个解决的问题。
简而言之,GC可以遍历已知静态和堆栈对象的引用网页,并且可以
将所有找到的对象复制到一个新的内存池中,自动留下任何“死”对象(这是“年轻一代”策略),或者 标记找到的所有对象,以便一旦遍历整个引用网络,就可以删除所有未标记的对象(这是“旧/新生代”策略)。they contain loop references to each other, they are accessible to each other.
Yes, but they aren't anymore accessible from anywhere else, so they can't be seen and used in the program anymore.
Early GCs had problems collecting such self-referencing object groups but with modern generational collectors it is a solved problem.
In brief, the GC can walk through the web of references from the known static and stack objects, and either
copy all objects found to a new memory pool, automatically leaving behind any "dead" objects (this is the "young generation" strategy), or mark all objects found, so that once the whole web of references is walked traversed, it can delete all unmarked objects (this is the "old/tenured generation" strategy).更多推荐
发布评论