简体   繁体   中英

Free heap memory with null then GC

Suppose I have this code:

DataStructure hugeData = Data.readLotsOfStuff(); // like gigabytes
DataStructure processedData = processData(hugeData);
// now I don't need hugeData, so
hugeData = null;
System.gc();

Is explicitly freeing memory like this a good practice?

It is generally not a good practice to care about those things. It makes the code harder to read (each additional line takes time to read) and in case of System.gc() all cases of bad runtime behaviour could happen. It will confuse the internal garbage collector predictions and typically trigger a very heavy/slow GCs. (Especially if your code is used in a larger application with concurrent uses it is hell).

Nulling a local variable (hard reference) early has issues:

a) if your reference is only used up to a certain point and your code block is much larger, then likely it is too large.

b) it is good to make local variables final, you can better read the code if you know the variable does not change. And those final variables cannot be nulled, anyway.

c) Java (runtime) compilers and interpreters get smarter by the minute. Let the VM decide when to free references.

Having said all that. If you leave the scope/block for a variable inside a method, you cannot expect the referenced object to become unreachable. It looks good to have variables narrow scoped, but for the problem of early freeing the reference it does not do much (unless a later scope re-uses the slot). If the method is long running (maybe a endless loop) it might be good to null the reference. But only if you reference a very large object tree which substantially would keep objects alive. Otherwise the additional assignment and code is not worth it.

method() {
  if (...) {
    byte[] ref=new byte[1*MB];
  }
  // B
  while(true) { ... }
}

In this example the large 1MB buffer is not in scope of location 'B', but it is still on the runtime java stack (java VM has no concept of scopes, ref is kept in a local variable table slot till the method is left). Since the method will not terminate (soon), it might be acceptable to null it. Splitting up the method is the better idea.

And never call System.gc().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM