问题描述
如何防止对象被垃圾回收?
How to prevent an object from getting garbage collected?
有没有通过 finalize 或 phantom reference 或任何其他方法的方法?
Are there any approaches by finalize or phantom reference or any other approaches?
我在一次采访中被问到这个问题.面试官建议可以使用finalize()
.
I was asked this question in an interview. The interviewer suggested that finalize()
can be used.
推荐答案
持有参考.如果您的对象被过早收集,则表明您的应用程序设计中存在错误.
Hold a reference. If your object is getting collected prematurely, it is a symptom that you have a bug in the design of your application.
垃圾收集器只收集应用程序中没有引用的对象.如果没有对象会自然引用收集到的对象,请问问自己为什么要保持它处于活动状态.
The garbage collector collects only objects to which there is no reference in your application. If there is no object that would naturally reference the collected object, ask yourself why it should be kept alive.
您通常没有引用但想要保留对象的一个用例是单例.在这种情况下,您可以使用静态变量.单例的一种可能实现如下所示:
One usecase in which you typically have no references, but want to keep an object is a singleton. In this case, you could use a static variable. One possible implementation of a singleton would look like this:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqInstance;
}
}
从技术上讲,您可以在终结器中的某处存储引用.这将阻止对象被收集,直到收集器再次确定没有更多引用为止.然而,终结器最多只会被调用一次,所以你必须确保你的对象(包括它的超类)在第一次收集之后不需要被终结.但是,我建议您不要在实际程序中使用此技术.(这会让像我这样的同事大喊 WTF!?;)
Technically, you can store a reference somewhere in your finalizer. This will prevent the object from being collected until the collector determines again that there are no more references. The finalizer will only be called at most once, however, so you must ensure that your object (including its superclasses) need not be finalized after the first collection. I would advise you, however, not to use this technique in actual programs. (It will leave colleagues like me yelling WTF!? ;)
protected void finalize() throws Throwable {
MyObjectStore.getInstance().store(this);
super.finalize(); // questionable, but you should ensure calling it somewhere.
}
这篇关于如何防止对象被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!