拓冰建站拓冰建站
首页 / 资讯中心 / 正文

JUC之集合类不安全

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

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门