java垃圾回收机制---面试的问题

来源:互联网 发布:哈尔滨公交车查询软件 编辑:程序博客网 时间:2024/06/05 19:19

面试过程中遇到一个问题:

 java 垃圾回收器,回收没有引用指向的对象实例,那如果是A->B,B->A这种就一直回收不了了吗?


Q: Does unreachable mean when there are no more references to the object?
A: No, but that is a common misunderstanding of garbage collection. You might think that the garbage collector keeps count of how many references there are to an object and then frees the object when the reference count is zero. However, it is easy to come up with a situation in which two objects need to be garbage collected, but each object has a reference to the other. If reference counting was being used, these two objects would never be freed.
问:当对象没有引用指向它时,就是unreachable吗?
答:不是,但这是关于垃圾回收的一个常见误解。你可能以为垃圾回收器会记录一个对象有多少个引用,当引用数为0时,就清理掉那个对象。但是,有一种很容易遇到的情况是,有2个对象需要被垃圾回收,但他们各自有一个指向对方的引用。如果使用引用数的话,这两个对象就永远不会被清理掉。

这两个对象, 如果没有第三方引用到其中之一, 也就是外界无法访问到这两对象

只有互相引用的话 

这两个对象会连在一起 成为垃圾

可以被回收

这两个对象虽然有相互的引用,但是他们两个是无法使用的,因为没有外部引用指向其中任何一个对象,原来这就是unreachable的含义。

2 0
原创粉丝点击