Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear objects (HashMap) to be garbage collected - Java

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

like image 387
Abdelrahman Shoman Avatar asked Feb 09 '15 10:02

Abdelrahman Shoman


People also ask

How can you make sure an object is garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.

Is HashMap garbage collected?

HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates over Garbage Collector.


2 Answers

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.
like image 110
Thilo Avatar answered Nov 09 '22 07:11

Thilo


 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

like image 42
shikjohari Avatar answered Nov 09 '22 05:11

shikjohari