Java7 WeakHashMap isEmpty() seems wrong

Peng :

I'm trying to use Java7's WeakHashMap and I found its isEmpty() method give me wrong results.

import java.util.Map;
import java.util.WeakHashMap;

public class Test
{

    public static void main(final String[] args)
    {
        final Map<String, Boolean> map = new WeakHashMap<>();

        String b = new String("B");
        map.put(b, true);
        b = null;

        System.gc();
        System.out.println(map.isEmpty());
        System.out.println(map.keySet().isEmpty());
        System.out.println(map);
    }

}

The actual result:

false

true

{}

That is to say,

map.isEmpty() and map.keySet().isEmpty() is not consistent. Can someone help me to understand it? Thanks a lot.

Not a JD :

WeakHashMap::isEmpty says:

...This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.

So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:

public class Scratch1 {
    public static void main(final String[] args) {
        final Map<String, Boolean> map = new WeakHashMap<>();

        String b = new String("B");
        map.put(b, true);
        b = null;

        System.gc();

        // map not internally accessed at this point
        System.out.println(map.isEmpty());

        // let's access the Map's internals (and hopefully coerce
        // it into removing no-longer-referenced keys)
        System.out.println(map.keySet()
                              .isEmpty());

        // map HAS now been accessed
        System.out.println(map.isEmpty());
    }

}

Yields:

false
true
true

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72910&siteId=1