Skip to content

Instantly share code, notes, and snippets.

@eribeiro
Last active January 5, 2017 14:34
Show Gist options
  • Save eribeiro/8512781 to your computer and use it in GitHub Desktop.
Save eribeiro/8512781 to your computer and use it in GitHub Desktop.
If you are using a *WeakHashMap* and your keys are boxed primitive types like, for example, an Integer with value 10, then you should *NOT* use "Integer.valueOf(10)" or even rely on autoboxing -- e.g., map.put(10, "blabla") -- to populate the keys of this map. REASON: both ".valueOf()" and autoboxing do a *caching* of primitive values (up to a t…
WeakHashMap<Integer, String> map = new WeakHashMap<Integer, String>();
map.put(new Integer(10), "aaa"); // remove entry
// map.put(10, "aaa"); // don't remove entry
// map.put(Integer.valueOf(10), "aaa"); // don't remove entry
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (map.size() != 0) {
System.out.println("At iteration " + i + " the map still holds the reference to object");
} else {
System.out.println("Object has finally been garbage collected at iteration " + i + ", the map is now empty");
break;
}
}
@eribeiro
Copy link
Author

eribeiro commented Jan 5, 2017

... up 127 (in fact, a range from in the range -128 to 127, inclusive) and may cache other values outside of this range. Therefore the Map entry is never removed because it will hold a strong reference (from the internal cache).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment