Explicit nulling

前端 未结 7 1239
再見小時候
再見小時候 2020-12-14 23:17

In what situations in java is explicit nulling useful. Does it in any way assist the garbage collector by making objects unreachable or something? Is it considered to be a g

7条回答
  •  星月不相逢
    2020-12-15 00:03

    One special case I found it useful is when you have a very large object, and want to replace it with another large object. For example, look at the following code:

    BigObject bigObject = new BigObject();
    // ...
    bigObject = new BigObject(); // line 3
    

    If an instance of BigObject is so large that you can have only one such instance in the heap, line 3 will fail with OutOfMemoryError, because the 1st instance cannot be freed until the assignment instruction in line 3 completes, which is obviously after the 2nd instance is ready.

    Now, if you set bigObject to null right before line 3:

    bigObject = null;
    bigObject = new BigObject(); // line 3
    

    the 1st instance can be freed when JVM runs out of heap during the construction of the 2nd instance.

提交回复
热议问题