当前位置:网站首页>Unsafe concurrency of collection classes
Unsafe concurrency of collection classes
2022-06-22 06:17:00 【Kuxiaoya】
There are many concurrent unsafe objects in collection classes , Has caused unsafe problems !
Such as :ArrayList、ArraySet、HashMap( Began in jdk1.2) It's not thread safe , It's possible to report
java.util.ConcurrentModificationExceptionConcurrent modification exception
We can do it in jdk1.8 See in help document , Since this release, it has provided many safe Thread objects for us to use !

ArrayList It's not safe
The solution is as follows :
Method 1 :Vector Replace ArrayListList<String> list = new Vector<>();
Method 2 :Collections( Collection tool class ) Provides methods for converting unsafe classes to safe classesList<String> list = Collections.synchronizedList(new ArrayList<>());
Method 3 :JUC The provided read-write security collection class :CopyOnWriteArrayListList<String> list = new CopyOnWriteArrayList<>();
The code is as follows :
package com.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListTest {
public static void main(String[] args) {
// And send it ArrayList unsafe
/** * Solution * 1、List<String> list = new Vector<>(); * 2、List<String> list = Collections.synchronizedList(new ArrayList<>()); * 3、List<String> list = new CopyOnWriteArrayList<>(); */
//List<String> list = new Vector<>();
//List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
ArraySet It's not safe
The solution is as follows :
Method 1 :Collections( Collection tool class ) Provides methods for converting unsafe classes to safe classesSet<String> set = Collections.synchronizedSet(new HashSet<>());
Method 2 :JUC The provided read-write security collection class :CopyOnWriteArraySetSet<String> set = new CopyOnWriteArraySet<>();
The code is as follows :
package com.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
/** * The same is true :ConcurrentModificationException Concurrent modification exception ! * Solution : * 1、 Set<String> set = Collections.synchronizedSet(new HashSet<>()); * 2、Set<String> set = new CopyOnWriteArraySet<>(); */
public class SetTest {
public static void main(String[] args) {
//Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i <= 10; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
HashMap It's not safe
The solution is as follows :
Method 1 :Collections( Collection tool class ) Provides methods for converting unsafe classes to safe classesMap<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
Method 2 :JUC The provided read-write security collection class :ConcurrentHashMapMap<String,String> map = new ConcurrentHashMap<>();
The code is as follows :
package com.unsafe;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.Collections.synchronizedMap;
/** * ConcurrentModificationException Concurrent modification exception ! * resolvent : * 1、Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>()); * 2、Map<String,String> map = new ConcurrentHashMap<>(); */
public class MapTest {
public static void main(String[] args) {
//Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
Map<String,String> map = new ConcurrentHashMap<>();
for (int i = 1; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
Summarized below :
1、 CopyOnWrite
Due to the use of “ When writing copy ” Thought , Apply to “ Read more and write less ” Scene ;
Because the original array will be copied when writing , It will occupy a large amount of memory , It is not applicable to scenarios with large amount of data ;
Only the final data consistency can be guaranteed , Real time data consistency cannot be guaranteed —— Read operations can only read data from old arrays , At this point, a new array may have been copied , And is modifying the data of the new array .
Iterations are performed on snapshots , Don't throw ConcurrentModificationException, And modification is not supported in the iteration process .
2、ConcurrentHashMap Principle analysis
One 、 Background
1、 Thread unsafe HashMap
Because in multithreaded environment , Use Hashmap Conduct put Operation can cause a dead cycle , Lead to CPU The utilization rate is close to 100%, So you can't use HashMap.
2、 Inefficient HashTable Containers
ConcurrentHashMap Lock segmentation technology used , First of all, the data is divided into pieces of storage , Then each piece of data is equipped with a lock , When a thread occupies a lock to access one of the segment data , Other segments of data can also be accessed by other threads .
3、ConcurrentHashMap Lock segment technology based on
ConcurrentHashMap Lock segmentation technology used , First of all, the data is divided into pieces of storage , Then each piece of data is equipped with a lock , When a thread occupies a lock to access one of the segment data , Other segments of data can also be accessed by other threads .
ConcurrentHashMap By Segment Array structure and HashEntry Array structure composition .
Segment The structure and HashMap similar , Is an array and linked list structure , One Segment It contains a HashEntry Array , Every HashEntry Is an element of a linked list structure , Every Segment Guarding a HashEntry The elements in the array , When the HashEntry When the data of the array is modified , Must first obtain its corresponding Segment lock .
Two 、 Principle analysis :
1、HashMap Right and wrong synchronized, Thread unsafe ,
2、 and Hashtable It's thread safe , Yes table Lock ;
3、conCurrentHashmap: Lock the barrel , Thread safe .
边栏推荐
猜你喜欢

经验模式分解(EMD)和希尔伯特-黄变换(HHT)
![tab[i = (n - 1) & hash] 的详细解读](/img/be/3e84b3e8406833c2a235494f1a035f.png)
tab[i = (n - 1) & hash] 的详细解读
![[NAND file system] UBI introduction](/img/69/7213b8b39cebc1626eb6bb8cc10d16.png)
[NAND file system] UBI introduction

Shengxin visualization (Part4) -- correlation diagram

C#中的数组及Foreach遍历

Research on automatic landing control system of carrier aircraft

Callable

SQL injection vulnerability (XI) wide byte injection

线程池的七大参数及自定义线程池

用蒙特卡洛法求圆周率pi
随机推荐
Markdown中插入类图(classDiagram)
生产者和消费者问题
878. the nth magic number math + two points
Single cell thesis records (part9) -- spatial charting of single cell transcriptomes in lectures
单细胞论文记录(part12)--Unsupervised Spatial Embedded Deep Representation of Spatial Transcriptomics
matlab 的离散pid控制
集合类并发不安全问题
Little bear school bearpi HM micro officially integrated into openharmony trunk
文献记录(part106)--GRAPH AUTO-ENCODER VIA NEIGHBORHOOD WASSERSTEIN RECONSTRUCTION
The difference between drop, truncate and delete
reduce_ Reduction in sum()_ indices
性能对比分析
从入门到精通之专家系统CLIPS(一)CLIPS初识与概述
Information system project management - scope management (focus)
Mail sending function is realized through SMTP protocol and exchange
tab[i = (n - 1) & hash] 的详细解读
IO密集型和CPU密集型
pip升级难题(已解决)You are using pip version 19.0.3, however version 22.1.2 is available.
Single cell paper record (Part14) -- costa: unsupervised revolutionary neural network learning for St analysis
生信可视化(part2)--箱线图