由于多重对象引用而导致的java垃圾收集
car_object_1
能够进行垃圾收集吗?有人坚持认为,由于 car_object_1
有两个引用,因此它永远不会被车库收集。这是真的吗?
Car createACar()
{
Car c = new MyCar(); //car_object_1 was created
return c;
}
void use_the_car()
{
Car c2 = createACar();
c2.run();
}
Will the car_object_1
be able to garbage collected? Somebody maintain that as car_object_1
has two reference so it will never be garaged collected. Is it true?
Car createACar()
{
Car c = new MyCar(); //car_object_1 was created
return c;
}
void use_the_car()
{
Car c2 = createACar();
c2.run();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,他们在胡说八道。假设
run()
中没有任何内容将引用隐藏在某处,则在use_the_car
c2.run(); 语句之后,汽车有资格进行垃圾回收代码>.Java不引用计数 - 即使循环引用也不是问题(例如,
Car
和Driver
相互引用,但没有任何内容涉及到他们中的任何一个)。也许与你交谈的人正在考虑稍微不同的情况?
No, they're talking nonsense. Assuming there's nothing within
run()
which stashes a reference somewhere, the car is eligible for garbage collection after thec2.run();
statement inuse_the_car
.Java is not reference counted - even circular references aren't a problem (e.g. where a
Car
and aDriver
have a reference to each other, but nothing has a reference to either of them).Perhaps the person you were talking to was thinking of a slightly different situation?