如何防止垃圾收集对象? [英] How to prevent an object from getting garbage collected?

查看:173
本文介绍了如何防止垃圾收集对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止对象被垃圾收集?



是否有通过finalize或phantom引用或任何其他方法的方法?

我在接受采访时被问到了这个问题。面试官建议可以使用 finalize()

解决方案

保留参考。如果你的对象过早被收集,这是你的应用程序设计中有一个错误的症状。



垃圾收集器只收集没有参考你的应用程序。如果没有对象会自然引用收集的对象,请问自己为什么应该保持活动。



一个用例,其中通常没有引用,但想要保持一个对象是一个单身人士。在这种情况下,你可以使用一个静态变量。一个可能的单例实现将如下所示:

  public class Singleton {
private static Singleton uniqueInstance;

私有Singleton(){
}

公共静态同步Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
返回uniqInstance;


编辑:您可以在终结器中的某处存储引用。这将阻止对象被收集,直到收集器再次确定没有更多的引用。然而,终结器最多只能被调用一次,所以你必须确保你的对象(包括它的超类)在第一次收集后不需要被终结。但是,我建议你不要在实际的程序中使用这种技术。 (它会让像我这样的同事大喊WTF !?)

  protected void finalize()throws Throwable {
MyObjectStore.getInstance()。store(this);
super.finalize(); //值得怀疑,但你应该确保将它称为某个地方。
}


How to prevent an object from getting garbage collected?

Are there any approaches by finalize or phantom reference or any other approaches?

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;
  }
}

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.
  }

这篇关于如何防止垃圾收集对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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