Which Java Collections are synchronized(thread safe), which are not?

前端 未结 10 2057
礼貌的吻别
礼貌的吻别 2020-12-16 11:05

Which Java Collections are synchronized, which are not?

Example: HashSet is not synchronized

相关标签:
10条回答
  • 2020-12-16 11:46

    You can get a synchronized version of a Java Collection with

    Collections.synchronizedCollection(Collection<T> c)
    

    [javadoc]

    0 讨论(0)
  • 2020-12-16 11:46

    ArrayList, LinkedList, HashSet,LinkedHashset and TreeSet in Collection Interface and HashMap,LinkedHashMap and Treemap are all non-synchronized.

    Vector in Collection Interface is Synchronized

    0 讨论(0)
  • 2020-12-16 11:46

    I guess each implementation of collection API has it written in documentation.

    0 讨论(0)
  • 2020-12-16 11:49

    All collection classes (except Vector and Hashtable) in the java.util package are not thread-safe. The only two legacy collections are thread-safe: Vector and Hashtable. WHY? Here’s the reason: Synchronization can be very expensive! You know, Vector and Hashtable are the two collections exist early in Java history, and they are designed for thread-safe from the start (if you have chance to look at their source code, you will see their methods are all synchronized!). However, they quickly expose poor performance in multi-threaded programs. As you may know, synchronization requires locks which always take time to monitor, and that reduces the performance. That’s why the new collections (List, Set, Map, etc) provide no concurrency control at all to provide maximum performance in single-threaded applications.

    0 讨论(0)
  • 2020-12-16 11:51

    Easy answer: not a single implementation of Collection is synchronized because synchronized is not a class property, it is only applicable to methods and blocks.

    I guess, you want to know which implementations are thread safe, which classes from the java collection framework can safely be used in a multithreaded environment.

    The information is always included in the javadoc (like here: Arraylist - which is not thread safe)

    0 讨论(0)
  • 2020-12-16 11:55

    Thread safe Collections -

    1. ConcurrentHashMap

    Thread safe without having to synchronize the whole map Very fast reads while write is done with a lock No locking at the object level Uses multitude of locks.

    1. SynchronizedHashMap

    Object level synchronization Both read and writes acquire a lock Locking the collection has a performance drawback May cause contention

    1. Vector

    2. HashTable

    3. CopyOnWriteArrayList

    4. CopyOnWriteArraySet

    5. Stack

    Rest all are not thread safe

    0 讨论(0)
提交回复
热议问题