Is it a good practice to remove references to help

2020-03-03 07:26发布

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

7条回答
Evening l夕情丶
2楼-- · 2020-03-03 08:13

It's certainly not bad practice to assign null to references if you don't want to use that object anymore. However, it is bad practice to count on the GC to collect them at any point soon or at all during your program's execution.

查看更多
登录 后发表回答