如何防止对象被垃圾收集?
是否有任何通过最终确定或幻像引用或任何其他方法的方法?
我在一次采访中被问到这个问题。面试官建议finalize()
可以使用。
保留一个参考。如果您的对象过早被收集,则表明您的应用程序设计中存在错误。
垃圾收集器仅收集应用程序中没有引用的对象。如果没有对象可以自然地引用所收集的对象,那么问问自己为什么应该保持它的活动状态。
您通常没有引用但想要保留对象的一种用例是单例。在这种情况下,您可以使用静态变量。单例的一种可能的实现如下所示:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqInstance;
}
}
Edit: 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.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)