I have cache, implemented with WeakHashMap, like this:
private static WeakHashMap<Object, WeakReference<Object>> objects = new WeakHashMap<>();
I have an instance of class City:
City c = new City();
I now add this instance to my map like this:
objects.put(c, new WeakReference<Object>(c));
According to WeakHashMap jvm implementation, if key doesn't have strong references to it, it's deleted from the map (in its free time).
So, if my object 'c' is not used in the program anymore, it will be deleted from 'objects' map.
So far, so good.
But what happens if I have two maps?
private static WeakHashMap<Object, WeakReference<Object>> objects1 = new WeakHashMap<>();
private static WeakHashMap<Object, WeakReference<Object>> objects2 = new WeakHashMap<>();
City c = new City();
objects1.put(c, new WeakReference<Object>(c));
objects2.put(c, new WeakReference<Object>(c));
Will GC collect the object 'c' in this case?