开发者

Does variable = null set it for garbage collection

开发者 https://www.devze.com 2023-01-01 15:57 出处:网络
Help me settle a dispute with a c开发者_运维百科oworker: Does setting a variable or collection to null in Java aid in garbage collection and reducing memory usage? If I have a long running program and

Help me settle a dispute with a c开发者_运维百科oworker: Does setting a variable or collection to null in Java aid in garbage collection and reducing memory usage? If I have a long running program and each function may be iteratively called (potentially thousands of times): Does setting all the variables in it to null before returning a value to the parent function help reduce heap size/memory usage?


That's old performance lore. It was true back in 1.0 days, but the compiler and the JVM have been improved to eliminate the need (if ever there was one). This excellent IBM article gets into the details if you're interested: Java theory and practice: Garbage collection and performance


From the article:

There is one case where the use of explicit nulling is not only helpful, but virtually required, and that is where a reference to an object is scoped more broadly than it is used or considered valid by the program's specification. This includes cases such as using a static or instance field to store a reference to a temporary buffer, rather than a local variable, or using an array to store references that may remain reachable by the runtime but not by the implied semantics of the program.

Translation: "explicitly null" persistent objects that are no longer needed. (If you want. "Virtually required" too strong a statement?)


The Java VM Spec

12.6.1 Implementing Finalization Every object can be characterized by two attributes: it may be reachable, finalizer-reachable, or unreachable, and it may also be unfinalized, finalizable, or finalized.

A reachable object is any object that can be accessed in any potential continuing computation from any live thread. Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

Discussion

Another example of this occurs if the values in an object's fields are stored in registers. The program may then access the registers instead of the object, and never access the object again. This would imply that the object is garbage.

The object is reachable if it can be involved in any potential continuing computation. So if your code refers to a local variable, and nothing else refers to it, then you might cause the object to be collected by setting it to null. This would either give a null pointer exception, or change the behaviour of your program, or if it does neither you didn't need the variable in the first place.

If you are nulling out a field or an array element, then that can possibly make sense for some applications, and it will cause the memory to be reclaimed faster. Once case is creating a large array to replace an existing array referenced by a field in a class - if the field in nulled before the replacement is created, then it may relieve pressure on the memory.

Another interesting feature of Java is that scope doesn't appear in class files, so scope is not relevant to reachability; these two methods create the same bytecode, and hence the VM does not see the scope of the created object at all:

static void withBlock () {
    int x = 1;

    {
        Object a = new Object();
    }

    System.out.println(x+1);
}

static void withoutBlock () {
    int x = 1;

    Object a = new Object();

    System.out.println(x+1);
}


Not necessarily. An object becomes eligible for garbage collection when there are no live threads anymore that hold a reference to the object.

Local variables go out of scope when the method returns and it makes no sense at all to set local variables to null - the variables disappear anyway, and if there's nothing else that holds a reference the objects that the variables referred to, then those objects become eligible for garbage collection.

The key is not to look at just variables, but look at the objects that those variables refer to, and find out where those objects are referenced by your program.


It is useless on local variables, but it can be useful/needed to clear up instance variables that are not required anymore (e.g. post-initialization).

(Yeah yeah, I know how to apply the Builder pattern...)


That could only make some sense in some scenario like this:

public void myHeavyMethod() {
  List hugeList = loadHugeListOfStuff();  // lots of memory used
  ResultX res = processHugeList(hugeList); // compute some result or summary 
  // hugeList = null;  // we are done with hugeList
    ...
  // do a lot of other things that takes a LOT of time (seconds?)
  // and which do not require hugeList
   ...
}

Here it could make some benefit to uncomment the hugeList = null line, I guess.

But it would certainly make more sense to rewrite the method (perhaps refactoring into two, or specifying an inner scope).


Setting an object reference to null only makes it eligible for garbage collection. It does not necessarily free up the memory,which depends on when the garbage collector runs(which depends on JVM). When the garbage collector runs,it frees up the heap by deleting only the objects which are eligible for garbage collection.


It is a good to have. When you set objects to null, there is a possibility that the object can be garbage collected faster, in the immediate GC cycle. But there is no guaranteed mechanism to make an object garbage collected at a given time.

0

精彩评论

暂无评论...
验证码 换一张
取 消