DEV Community

ChelseaLiu0822
ChelseaLiu0822

Posted on

Thread safe collection class

Blocking: Based on locks, through blocking
CopyOnWrite: modification overhead is high
Containers of Concurrent type:
Through cas optimization, high throughput
Weak consistency: When traversing, even if the container is modified, the iterator can continue to traverse, and the content is old
Seek consistency between sizes and sizes. The size operation may not be 100% accurate.
Read weak consistency
If modifications occur during traversal of a non-thread-safe container, the fail-fast mechanism will be used to cause the traversal to fail and throw
ConcurrentModificationException, no longer traversed.

ConcurrentHashMap
Same as the normal HashMap method, but thread-safe
Although each operation is atomic, the combination is not necessarily thread-safe.
map.computeIfAbsent() puts the key into the map. It is thread-safe and ensures the atomicity of the get and put method combinations.
principle:
HashMap Java 8 hash conflict elements are placed at the end of the linked list, while in Java 7 they are placed at the head.
The problem of concurrent dead links will occur when HashMap is expanded (occurred in JDK 7). The insertion method has been modified in JDK 8 so that dead links will no longer be formed during expansion, but it will easily lead to data loss during expansion.
ConcurrentHashMap

Image description

Image description

Image description

Lazy initialization, only the table size is calculated in the construction method, and it is not actually created until it is used for the first time.
The structure used in JDK8 is array + linked list + red and black. The initial length of the array is 16
When the length of the linked list exceeds 8, it turns into a red tree. When the length exceeds the loading factor * array length, the capacity is expanded.
In JDK7, Segment segment lock is used to achieve thread safety based on array + linked list.
Using CAS+Synchronized in JDK 8 to ensure thread safety

Top comments (0)