删除引用以帮助GC是否是一种很好的做法? [英] Is it a good practice to remove references to help the GC?

查看:95
本文介绍了删除引用以帮助GC是否是一种很好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道您是否认为将对象的引用(将它们设置为 null )设置为对象以帮助Java垃圾收集器是一种很好的做法。



例如,假设您有一个包含两个字段的类,其中一个字段非常耗费内存。如果你知道你只需要一个特定的处理,你可以在帮助GC之后立即将它清空。

假设我真的需要这两个字段,而不是只有内部变量,所以 heavyObject1 不能在方法结束时超出范围。



你会这样做吗?作为一般做法吗?

  public class TestClass {

public static Object heavyObject1;
public static Object object2;

private static void action(){
object2 = doSomething(heavyObject1);

heavyObject1 = null; //这个好吗?
}
}


解决方案

通常这是不需要的。



在以下特定情况下,这是个好主意:


  • 该对象很大(即足够大以至于不在乎)

  • 您确定不再需要该对象 em>

  • 对象不会超出范围(例如,您知道周围的对象不会被垃圾收集)



但是,如果您发现自己处于这种情况下,我怀疑您有设计异味:为什么内部对象有这样的不同封闭对象的范围/生命周期?这让我感到怀疑,因为通常当你用合成建立一个对象图时,你期望合成对象的生命期相似。


I am wondering whether you would consider it a good practice to remove references (setting them to null) to objects in order to help the Java Garbage Collector.

For instance, let's say you have a class with two fields, one of them being very memory-consuming. If you know you only need it for a particular processing, you can null it right after to help the GC.

Assume I really need those two to be fields, and not only internal variables, so heavyObject1 cannot be out of scope at the end of the method.

Would you do this as a general practice?

public class TestClass {

   public static Object heavyObject1;
   public static Object object2;

   private static void action() {
    object2 = doSomething(heavyObject1);

    heavyObject1 = null; //is this good?
   }
}

解决方案

Usually it isn't needed.

It's a good idea in the following specific circumstance:

  • The object is large (i.e. large enough for you to care)
  • You are sure the object won't be needed again
  • The object won't go out of scope otherwise (e.g. you know the surrounding object won't be garbage collected)

However if you find yourself in this situation I suspect you have a design smell anyway: why does the internal object have such a different scope / lifetime from the enclosing object? This makes me suspicious, because usually when you build up an object graph with composition you expect the composed objects to have similar lifetimes.

这篇关于删除引用以帮助GC是否是一种很好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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