WeakHashMap may behave as though an unknown thread is silently removing entries.
The WeakHashMap.Entry
is a WeakReference
object whose referent is the key
object you passed to map.put()
. That's to say if the key
becomes weakly reachable
, the garbage collector will atomically declare it finalizable.
The Java SE 8 document says that:
An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.
In this line of your code
Integer obj = new Integer(200);
map.put(obj, "sgdjsgd");
the obj
is a strong refernce to the integer object created by new Integer(200)
and then it is passed to map.put()
which creates a WeakReference
(assuming it's called w
) to hold this integer object.
But after this line:
obj = new Integer(20);
The obj
points to another integer object that holds 20 (the w
still points to the integer object that holds 200).
But changing the object the obj
points to will make the referent of w
becomes weakly reachable
because it can only be reached by traversing a weak reference (namely the w
).
When control returns from the method call to System.gc()
, the JVM has made its best effort to recycle all discarded objects. So as is said above, the garbage collector will atomically declare weakly-reachable objects finalizable and finally clear them.
So the w
is cleared, the entry in the map is discarded by the garbage collector and as a result, your map contains nothing.