简体   繁体   中英

Is there a way to test when an element is removed from a weak set?

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?

As @Chai T.Rex properly mentioned in commentaries, strings is bad example for garbage collection. To see how objects are garbage collected from weak set try this modified version of your code:

    Set<Object> weakSet = Collections.newSetFromMap(new WeakHashMap<>());
    weakSet.add(new Object());
    System.out.println(weakSet.size()); // prints "1"
    while (weakSet.size() > 0)
        System.gc();
    System.out.println(weakSet.size()); // prints "0"

What generally happens here: we add new object into set ( weakSet.add(new Object()) ). But because we do not keep any reference on it, GC will find this object will be removed from set.

Loop on GC is needed, as garbage collecting in this simple example case is not guaranteed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM