目录
一、集合类HashSet线程不安全的代码示例
- 一、集合类HashSet线程不安全的代码示例
- 二、集合类HashSet线程不安全的故障现象
- 三、集合类HashSet线程不安全的原因
- 四、集合类HashSet线程不安全的解决方案
- 4.1、解决方式一:通过Collections工具类解决
- 4.2、解决方式二:通过JUC包下的写时复制集合类解决
- 五、CopyOnWriteArraySet线程安全的源码解析
-
代码
import java.util.*; /** * @description: HashSet线程不安全的代码示例 * @author: xz */ public class ContainerNotSafe { public static void main(String[] args) { Set set=new HashSet(); //模拟30个线程,往HashSet集合中添加数据 for(int i=1;i{ set.add(UUID.randomUUID().toString().substring(0,8)); System.out.println(set); }).start(); } } }
-
输出结果如下:
- 报 java.util.ConcurrentModificationException 异常错误
- 并发争抢修改导致报 java.util.ConcurrentModificationException 异常错误。
-
代码
import java.util.*; /** * @description: 通过Collections工具类解决集合类HashSet线程不安全问题 * @author: xz */ public class ContainerNotSafe { public static void main(String[] args) { Set set=Collections.synchronizedSet(new HashSet()); //模拟30个线程,往synchronizedSet集合中添加数据 for(int i=1;i{ set.add(UUID.randomUUID().toString().substring(0,8)); System.out.println(set); }).start(); } } }
-
输出结果如下:
-
jdk1.8 API中的写时复制集合类截图如下:
-
代码
import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; /** * @description: 通过JUC包下的写时复制集合类解决HashSet线程不安全问题 * @author: xz */ public class ContainerNotSafe { public static void main(String[] args) { Set set=new CopyOnWriteArraySet(); //模拟30个线程,往CopyOnWriteArraySet集合中添加数据 for(int i=1;i{ set.add(UUID.randomUUID().toString().substring(0,8)); System.out.println(set); }).start(); } } }
-
输出结果如下:
- 源码如下
- 【上图解释】
- 由上图可知,CopyOnWriteArraySet线程安全集合类底层调用的是CopyOnWriteArrayList线程安全集合类。
- CopyOnWriteArrayList线程安全集合类的源码解析,请参考lz此博文链接: https://wwwxz.blog.csdn.net/article/details/122442016