List thread insecurity and solution
/**
* list 线程不安全,可能出现ConcurrentModificationException并发修改异常
*/
public class ThreadDemo4 {
public static void main(String[] args) {
//创建ArrayList集合
// List<String> list = new ArrayList<>();
//解决方案1: Vector
// List<String> list = new Vector<>();
//解决方案2: Collections.synchronizedList
// List<String> list = Collections.synchronizedList(new ArrayList<>());
//解决方案3: CopyOnWriteArrayList
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 300; i++) {
new Thread(()->{
//向集合添加内容
list.add(UUID.randomUUID().toString().substring(0,8));
//从集合索引内容
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
Solution - Vector
The add method of Vector is added with the synchronized keyword, which is a very old solution
Solutions - Collections
List<String> list = Collections.synchronizedList(new ArrayList<>());
Not very efficient and not used much
Solution - CopyOnWriteArrayList
It comes from the principle of CopyOnWriteArrayList under the JUC package : copy-on-write technology, copy the same copy when writing, add new content, and then overwrite the previous one.
HashSet, HashMap thread insecurity and solutions
// Set<String> set = new HashSet<>();
//HashSet解决方案:CopyOnWriteArraySet
// Set<String> set = new CopyOnWriteArraySet<>();
// Map<String, String> map = new HashMap<>();
//HashMap解决方案:ConcurrentHashMap
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 300; i++) {
String key = String.valueOf(i);
new Thread(()->{
//向集合添加内容
map.put(key, UUID.randomUUID().toString().substring(0,8));
//从集合索引内容
System.out.println(map);
},String.valueOf(i)).start();
}