Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is concurrentMap.keySet().toArray() thread safe?

I have a ConcurrentHashMap<String, Object> concurrentMap;

I need to return String[] with keys of the map.

Is the following code:

  public String[] listKeys() {
    return (String[]) concurrentMap.keySet().toArray();
  }

thread safe?

like image 703
Vitaly Avatar asked Oct 22 '25 07:10

Vitaly


2 Answers

While the ConcurrentHashMap is a thread-safe class, the Iterator that is used on the keys is NOT CERTAIN to be in sync with any subsequent HashMap changes, once created...

From the spec:

    public Set<K> keySet()

    Returns a Set view of the keys contained in this map......
    ...........................

    The view's iterator is a "weakly consistent" iterator that will 
    never throw ConcurrentModificationException, and guarantees to 
    traverse elements as they existed upon construction of the iterator, 
    and may (but is not guaranteed to) reflect any modifications 
    subsequent to construction.
like image 103
Mechkov Avatar answered Oct 24 '25 22:10

Mechkov


Yes and No. Threas-safe is only fuzzily defined as soon as you extend to scope.

Generally, concurrent collections implement all their methods in ways that allow concurrent access by multiple threads, or if they can't, provide mechanisms to serialize such accesses (e.g. synchronization) transparently. Thus, they are safe in the sense they ensure they preserve a valid internal structure and method calls give valid results.

The fuzziness starts if you look at the details, e.g. toArray() will return you some kind of snapshot of the collections contents. There is no guarantee that by the time the method returns the contents will not have already been changed. So while the call is thread safe, the result will not fulfill the usual invariants (e.g. the array contents may not be the same as the collections).

If you need consistency over the scope of mupltiple calls to a concurrent collection, you need to provide mechanisms within the code calling the methods to ensure the required consistency.

like image 30
Durandal Avatar answered Oct 24 '25 22:10

Durandal