Java Concurrency programming: synchronizing containers
Organized by: Blog Park-Haizi-http://www.cnblogs.com/dolphin0520/p/3933404.html
1. Causes of synchronization container
Common Arraylist,linkedlist,hashmap,hashset,deque, etc. are thread insecure;
Java is a convenient multi-threading program that provides a synchronization container for users to use.
2. Synchronous Container class:
2.1: First class: Vector (ArrayList), Stack (subclass of Vector), HashTable (HASHMAP)
2.2: Class II: Classes created by the static factory method provided in the collections class. such as collections.synchronizedxxx () gets
3, the defect of the synchronization container:
3.1: Use the Synchronized keyword to synchronize to reduce the efficiency;
3.2: Like vector this add and get methods are synchronized, in multithreaded read, competition lock, inefficient.
3.3: A Concurrentmodificationexception exception may be thrown when a multithreaded operation synchronizes a container.
4. Concurrentmodificationexception abnormal causes and solutions
4.1: Single-threaded: iterator iterator iteration, call the list of remove to modify the container size, you should call the iterator Remove method;
4.2: Multi-threaded: Multiple threads execute iterator and modify, at which point the iterator thread is private.
Correct: When "1" gets iterator, use synchronized or lock to synchronize.
"2" replaces ArrayList and vectors with concurrent container copyonwritearraylist
5, concurrent containers: Java.util.concurrent Package
The synchronization container will serialize all access to the container state, ensuring the security, but reducing the efficiency;
5.1:concurrenthashmap replaces the synchronized map (collections.synchronized (new HashMap ()), HashMap locks all segments when synchronizing, and Concurrenthashmap only lock the corresponding segment (segment);
5.2:copyonwritearraylist and Copyonwritearrayset replace list and set respectively, and copy list and copy set when writing.
5.3: Other
Java Concurrency Mechanism (5)--synchronization container and concurrent container