In the following snippet (whose only purpose is educational testing), contains()
always ↲ true.
Set<String> weakSet = Collections.newSetFromMap(new WeakHashMap<>());
weakSet.add("someKey");
System.gc();
weakSet.contains("someKey");
I would expect that the best effort done by the JVM to reclaim space includes removing objects that are only weakly reachable (weak set elements without any strong references). But I'm wrong.
So, is there a way to test in practice the automatic removal of weak references, so you can see the reference gone? In other words, how to have contains()
return false?