SCJP模拟问题:有多少个对象符合垃圾回收的条件?(SCJP Mock Question: How many objects are eligible for garbage collection?)

系统教程 行业动态 更新时间:2024-06-14 17:01:34
SCJP模拟问题:有多少个对象符合垃圾回收的条件?(SCJP Mock Question: How many objects are eligible for garbage collection?)

我被问到一个问题(在这个网站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).

更多推荐

本文发布于:2023-04-20 18:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/e36e758367c32080f120a49346816f9f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有多少个   对象   垃圾   条件   SCJP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!