Lolo
Lolo

Reputation: 4159

Why does a hashmap clear() free more memory than a pointer reassignment

I have an old and new map that contain hundred thousand entries:

Map<State, CostAndIndex> oldMap = new LinkedHashMap<State, CostAndIndex>();
Map<State, CostAndIndex> newMap = new LinkedHashMap<State, CostAndIndex>();

At the end of each iteration of a loop, I was simply doing this:

oldMap = newMap;

With that approach I was running out of memory after a while, even when calling System.gc(); after the reassignment.

Then I added a clear before the reassignment and I no longer run out of memory.

oldMap.clear();
oldMap = newMap;

My question: Why does it change anything? Doesn't a pointer reassignment tell Java that the map and its content are no longer needed and it can clear the data and reuse the space for whatever purpose?

Note: This is running Java HotSpot 1.7. With Java HotSpot 1.6, I run out of memory much more quickly with the first approach, which isn't clear to me why either.

Upvotes: 1

Views: 1860

Answers (1)

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18148

You are correct, it shouldn't make any difference in terms of memory - you must have another reference to oldMap floating around that's preventing it from being GC'd (if object1 and object2 both point to oldMap, and you update object1 to point to newMap, then object2 will still be pointing to oldMap which will prevent it from being GC'd)

Upvotes: 2

Related Questions