5.集合类不安全之Set


package com.mydemo;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

public class SetNotSafeDemo {
    public static void main(String[] args) {
        //HashSet set = new HashSet<>();
        //CopyOnWriteArraySet set = new CopyOnWriteArraySet<>();
        Set set = Collections.synchronizedSet(new HashSet());
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
            
        }
    }
}

解决方法:

  1. Collections.synchronizedSet(new HashSet<>())
  2. CopyOnWriteArraySet<>()(推荐)

2.HashSet底层是HashMap

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

相关