如果垃圾回收器尚未删除未引用的对象,它们是否仍可以运行? [英] Can unreferenced objects still run if the garbage collector hasn't deleted them?

查看:71
本文介绍了如果垃圾回收器尚未删除未引用的对象,它们是否仍可以运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个对象正在等待被垃圾回收,但是包含一个线程,该线程在更改对该对象的最后一个引用时正在运行,那么该线程是否仍将运行并且代码仍将执行?那么,您是否可能会有一堆应该删除的幻影对象,但是它们会对您的代码产生影响?您如何防止这种情况?是否有一种方法可以告诉对象是否正在等待收集?

If an object is waiting to be garbage collected, but contains a thread that was running when the last reference to the object was changed, will that thread still run and will the code still execute? So could you potentially have a bunch of ghost objects that should be deleted, but are having an effect on your code? How do you prevent this? Is there a way for an object to tell if it is waiting to be collected?

推荐答案

在完成线程之前,不会对其进行垃圾回收,因此,如果您的线程从未完成,则将无法进行垃圾回收.正如fge在评论中所指出的,线程经常会引用封闭对象,这当然会防止线程被垃圾回收.

A thread wont be garbage collected until it has finished, so if your threads never finish, they will not be available for garbage collection. As noted by fge in the comments, often times the thread will have reference to the enclosing object, which will of course prevent the thread from being garbage collected.

要知道是否正在收集对象,请

As for knowing if an object is on its way to be collected, this answer has some nice details on what you can(and can't) do.

除此之外,您可以建议jvm使用system.gc()运行垃圾收集,但不能保证jvm将运行垃圾收集器.

Other than that, you can suggest the jvm to run garbage collection with system.gc(), but there is no guarantee the jvm will run the garbage collector.

这篇关于如果垃圾回收器尚未删除未引用的对象,它们是否仍可以运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆