如何确定应用程序中的特定对象不再使用?
我如何知道一个对象(或一个类的对象)是否正在使用并且准备好被 GC 收集。或者我如何知道该对象在应用程序运行时没有引用。 (在获得GCed之前)
How could I figure out that an object(or objects of a class) is/are not in use and ready to be collected by GC. or how could i get to know that object has no reference while the application is running. (before it gets GCed)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设你的意思是检测一个对象在运行时不再使用,而不是你可以静态检查的东西。
通知对象即将被GC 的最简单方法是重写finalize() 方法。注意:在这个方法中你必须小心你所做的事情。例如,它是单线程的,阻塞将导致没有对象被清理。
另一种方法是使用弱引用或软引用并监视引用队列。这是一种监视何时检测到可以清理对象的方法。有关示例,请参阅 WeakHashMap 的源代码。
注意:如果没有 GC,就没有简单的方法来检测对象是否不再使用,并且如果您很长一段时间没有 GC,那么您同时也无法知道。
I assume you mean detecting an object is no longer in use at run time, rather than something you can check staticly.
The simplest way to be notified that an object is about to be GCed is to override the finalize() method. Note: you have to be careful what you do in this method. e.g. It is single threaded and blocking will result in no objects being cleaned up.
Another approach is to use Weak or Soft References and monitor a ReferenceQueue. This is a way to monitor when an object has been detected as available to be cleaned up. See the source for WeakHashMap for an example.
Note: there is no simple way to detect an object is no longer in use without a GC, and if you don't have a GC for a long time, you have no way of knowing in the meantime.
在 Eclipse 中,您可以右键单击您的类,然后选择
References >项目
in Eclipse you can right-click your class, and select
References > Project
我使用 UCDetector(不必要的代码检测器) Eclipse 插件。它将向您显示没有引用的公共类、方法或字段,并允许您轻松删除它们。
I use the UCDetector (Unnecessary Code Detector) Eclipse plugin. It will show you public classes, methods or fields which have no references, and allow you to delete them easily.