0
votes


I have some HashMap < String, XYZ > created having the key type as String and value type of some XYZ Class.Now for some condition check I want to free/ garbage collect the entire HashMap along with the individual objects of XYZ type that it holds. Is it possible to do it without iterating the hash map and setting each object to null ? I guess by setting only HashMap to null will not work. How do I ensure later that the collection of objects is garbage collected ?

If I do something like:

XYZ obj = new XYZ();
hm.put("<unique-id>",obj);

XYZ obj2 = new XYZ();
hm.put("<unique-id>",obj2);

.
.
.<more operations>
.
.
hm = null;

my code no longer reference either obj or obj2 after hm=null statement.


So can I be sure enough that the jvm will garbage collect obj and obj2 also shortly ?


Moreover in cases where hashmap is a huge collection, I dont want to use Iterator over HashMap to get and iterate over every object and set it to null.

Does just hm=null does the above stuffs of GCing the entire collection of objects + map for me ?

1
A) You can't enforce GC. B) hashMap = null is enough if nothing else references the keys / values. - zapl
Does all the individual objects that HashMap holds will be automatically garbage collected ? - Dhwanit
Objects are garbage-collected when they are not reachable anymore from the running code. The GC is very smart, it also detects reference loops. But it's so smart that it won't get controlled by you. With the default settings, System.gc() is ignored, and the GC won't run at all*, unless you're using more than a given memory threshold. If you want yout map to be collected along with its contents, just set the map to null. No need to iterate. * it may perform some memory maintainance operations, but it won't "stop the world". - Giulio Franco

1 Answers

3
votes

If an object isn't referenced anymore, you can be sure that the object is garbage collected properly. That means, if you set the hash map to null and you know that all the items within the map arn't referenced by other objects, then they are garbage collected. In case you want to call the gcc manually keep in mind that the decision whether the gcc process is executed or not is ultimately made by the JVM!