how to clear objects (HashMap) to be garbage colle

2019-04-09 12:25发布

问题:

So what I am having here is a java program the manipulates a huge amount of data and store it into objects (Mainly hash-maps). At some point of the running time the data becomes useless and I need to discard so I can free up some memory.

My question is what would be the best behavior to discard these data to be garbage collected ?

I have tried the map.clear(), however this is not enough to clear the memory allocated by the map.

EDIT (To add alternatives I have tried)

I have also tried the system.gc() to force the garbage collector to run, however it did not help

回答1:

HashMap#clear will throw all entries out of the HashMap, but it will not shrink it back to its initial capacity. That means you will have an empty backing array with (in your case, I guess) space for tens of thousands of entries.

If you do not intend to re-use the HashMap (with roughly the same amount of data), just throw away the whole HashMap instance (set it to null).

In addition to the above:

  • if the entries of the Map are still referenced by some other part of your system, they won't be garbage-collected even when they are removed from the Map (because they are needed elsewhere)
  • Garbage collections happens in the background, and only when it is required. So you may not immediately see a lot of memory being freed, and this may not be a problem.


回答2:

 system.gc() 

is not recommended as jvm should be the only one to take care of all the garbage collection. Use Class WeakHashMap<K,V> in this case. The objects will automatically be removed if the key is no longer valid

Please read this link for reference