[concurrency-interest] ConcurrentHashMapV8

Bob Lee crazybob at crazybob.org
Fri Oct 7 16:52:02 EDT 2011


On Wed, Oct 5, 2011 at 6:11 AM, Doug Lea <dl at cs.oswego.edu> wrote:

> To me, fixing the mis-feature is more important
> than retaining pure compatibility for a usage
> that probably didn't do what people expected anyway.
> But if you've ever done anything relying on the old j.u.c
> behavior, could you let us know? Thanks!


Is it correct to assume that "fixing" CHM.entrySet().toArray() requires more
work on our part? If so, it's probably not worth the effort

If we assume the user wants a snapshot of the entry set, here's the code
using toArray():

    Set<Map.Entry<K, V>> original = map.entrySet();
    // This array isn't used outside of this code, so we can ignore the
warning.
    @SuppressWarnings("unchecked")
    Map.Entry<K, V>[] array = original.toArray(
        (Map.Entry<K, V>[]) new Map.Entry[0]);
    // We erroneously get an "unchecked generic array creation" warning
here.
    @SuppressWarnings("unchecked")
    Set<Map.Entry<K, V>> copy = new HashSet<Map.Entry<K, V>>(
        Arrays.asList(array));

Yuck. It requires two unsafe operations. We actually shouldn't get a warning
in the second case, and it'll go away either way with Java 7, but I do get a
warning with my current setup. Copying entries from a concurrent map to an
exact-length array is tricky and inefficient. The user can call size() and
use it to create the passed-in array, but the array size could change. It
can also change while copying the entries in which case toArray() may have
to create a copy. If the size goes down, the array needs to be truncated. If
the size goes up, any remaining entries are ignored.

It's simpler, safer, and more efficient for users to copy the entries
manually:

    Set<Map.Entry<K, V>> copy = new HashSet<Map.Entry<K, V>>(map.size());
    for (Map.Entry<K, V> entry : map.entrySet()) {
      copy.add(new AbstractMap.SimpleEntry<K, V>(entry));
    }

Thanks,
Bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20111007/aad6db23/attachment.html>


More information about the Concurrency-interest mailing list