Thread-safe iteration over a collection

后端 未结 8 1182
情歌与酒
情歌与酒 2020-12-05 05:21

We all know when using Collections.synchronizedXXX (e.g. synchronizedSet()) we get a synchronized \"view\" of the underlying collection.

Ho

相关标签:
8条回答
  • 2020-12-05 06:06

    All three of your options will work. Choosing the right one for your situation will depend on what your situation is.

    CopyOnWriteArrayList will work if you want a list implementation and you don't mind the underlying storage being copied every time you write. This is pretty good for performance as long as you don't have very big collections.

    ConcurrentHashMap or "ConcurrentHashSet" (using Collections.newSetFromMap) will work if you need a Map or Set interface, obviously you don't get random access this way. One great! thing about these two is that they will work well with large data sets - when mutated they just copy little bits of the underlying data storage.

    0 讨论(0)
  • 2020-12-05 06:08

    You could use one of the newer collections added in Java 5.0 which support concurrent access while iterating. Another approach is to take a copy using toArray which is thread safe (during the copy).

    Collection<String> words = ...
    // enhanced for loop over an array.
    for(String word: words.toArray(new String[0])) {
    
    }
    
    0 讨论(0)
提交回复
热议问题