由于多重对象引用而导致的java垃圾收集

发布于 2024-11-09 06:44:11 字数 276 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九命猫 2024-11-16 06:44:11

不,他们在胡说八道。假设 run() 中没有任何内容将引用隐藏在某处,则在 use_the_carc2.run(); 语句之后,汽车有资格进行垃圾回收代码>.

Java引用计数 - 即使循环引用也不是问题(例如,CarDriver 相互引用,但没有任何内容涉及到他们中的任何一个)。

也许与你交谈的人正在考虑稍微不同的情况?

No, they're talking nonsense. Assuming there's nothing within run() which stashes a reference somewhere, the car is eligible for garbage collection after the c2.run(); statement in use_the_car.

Java is not reference counted - even circular references aren't a problem (e.g. where a Car and a Driver 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文