Java Concurrency Mechanism (5)--Synchronous Containers and Concurrent Containers

Java Concurrent Programming: Synchronized Containers
Organized from: Blog Garden-Haizi-http://www.cnblogs.com/dolphin0520/p/3933404.html
1.
Commonly used ArrayList, LinkedList, HashMap, HashSet, Deque, etc. It is thread-unsafe;
Java provides synchronization containers for users to use to facilitate multi-threaded programming.
2. Synchronization container class:
2.1: The first class: Vector (ArrayList), Stack (subclass of Vector), HashTable (HashMap)
2.2: The second class: The class created by the static factory method provided in the Collections class. For example, Collections.synchronizedXxx() obtains
3. Defects of synchronized containers:
3.1: Using the synchronized keyword to synchronize reduces efficiency;
3.2: Both add and get methods like Vector are synchronized. When multi-threaded reading, it competes for locks, which is efficient very low.
3.3: ConcurrentModificationException may be thrown when the synchronization container is operated by multiple threads.
4. Causes and solutions of ConcurrentModificationException 4.1: Under single thread
: When the Iterator iterator is iterated, the size of the container is modified by calling the remove method of the list, and the remove method of the Iterator should be called;
At this point the Iterator thread is private.
Correction: [1] When obtaining Iterator, use synchronized or Lock synchronization.
[2] Use the concurrent container CopyOnWriteArrayList instead of ArrayList and Vector

5. Concurrent container: java.util.concurrent package
The synchronization container serializes all access to the container state, which ensures security, but reduces efficiency;
5.1: ConcurrentHashMap replaces the synchronized Map (Collections.synchronized (new HashMap() ), HashMap locks all segments when synchronizing, while ConcurrentHashMap only locks the corresponding segment (segment);
5.2: CopyOnWriteArrayList and CopyOnWriteArraySet replace List and Set respectively, copy List when writing and copy set when writing;
5.3: Other

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324644677&siteId=291194637