CopyOnWriteArraySet

HeJin小于 1 分钟JavaJUC并发编程

一般的HashSet

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();
        }
    }
}

线程不安全。报错。ConcurrentModificationException。

1、使用Collections工具类

Set<String> set = Collections.synchronizedSet(new HashSet<>());

2、使用CopyOnWriteArraySet

Set<String> set = new CopyOnWriteArraySet<>();

HashSet的底层

HashSet的底层就是HashMap。

public HashSet() {
    map = new HashMap<>();
}
image-20210311173049408
image-20210311173049408

HashSet的add方法

// set本质就是map的key,是无法重复的
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
// 不变的值
private static final Object PRESENT = new Object();
image-20210311173231966
image-20210311173231966