Threads and Collections

来源:互联网 发布:大数据预测性分析 编辑:程序博客网 时间:2024/04/29 13:17

 

Ever since JDK 1.2 collections are being widely used to store data in our programs. These Collection classes are used to store data which is shared by diferrent threads. Hence come the problem of which collection are thread-safe. i.e. Operations on these collection classes are synchronized.
If a collection class is not thread-safe and if we intend to use it in our multithreaded program, then we need to explicitely synchronize them.(or apply a wrapper class)
Some thread safe collection classes are:

  • Vector
  • Stack
  • Hashtable
  • ConcurrentHashMap
  • ConcurrentLinkedQueue
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet


Thread Unsafe Collection Classes: HashSet, TreeSet, HashMap, TreeMap, WeakHashMap, IdentityHashMap, LinkedHashMap etc.
How to achieve synchronization when working with Collections in multithreaded programs Can be done by:

  • Usage of a thread safe collection (:-) Seems Simple Huh...)
  • Manage synchronization explicitely by providely synchronized access to certain blocks of code.
  • Usage of a synchronized version of a Thread-Unsafe collection class
    • Map m = Collections.synchronizedMap(new HashMap());
    • Look into the synchronized_ _ mthods of the Collections class for more details.
原创粉丝点击