List不安全:
并发下,ArrayList是不安全的,报并发修改异常:ConcurrentModificationException
解决方案:Vector,
Collections.synchronizedList(new ArrayList<>());
concurrent包下的CopyOnWriteArrayList,CopyOnWrite写入时复制,COW,计算机程序设计领域的一种优化策略
多线程调用的时候,list,读取的时候,固定的,写入 (覆盖)
在写入的时候避免覆盖,造成数据问题。
读写分离
Set不安全:
public class SetTest{
public static void main(String[] args){
Set<String> set=new HashSet<>();
for(int i=1;i<=30;i++){
new Thread(()->{set.add(UUID.randomUUID().toString().substring(0,5)));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
会报并发修改错误。
解决方案:
Set<String> set=Collections.synchronizedSet(new HashSet<>());
Set<String> set=new CopyOnWriteArraySet<>();
hashSet底层?
hashSet底层就是hashMap
public HashSet(){
map=new HashMap<>();
}
//add set本质就是map,key是无法重复的
public boolean add(E e){
return map.put(e,PRESENT)==null;
}
private static final Object PRESENT=new Object();//不变的值
Map不安全:
public class MapTest{
public static void main(String[] args){
Map<String,String> map=new HashMap<>();
}
}
加载因子0.75,初始化容量16
public class MapTest{
public static void main(String[] args){
Map<String,String> map=new HashMap<>();
for(int i=1;i<=30;i++){
new Thread(()->{ map.put(Thread.currentThread().getName(),UUID.randomUUID().toString());
System.out.println();
},String.valueOf(i)
).start();
}
}
}
会出现并发修改异常
解决方法:
Map<String,String>map=new ConcurrentHashMap<>();