面试题:HashSet线程不安全,为什么不安全?CopyOnWriteArraySet为什么安全?
HashSet线程不安全,不安全的原因是因为HashMap不是线程安全的。在HashSet中,底层源码,其实就是一个HashMap,为HashMap的key为HashSet中的值,而value为一个Object对象常量。
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
// 构造方法:里面new了一个HashMap
public HashSet() {
map = new HashMap<>();
}
// HashSet.add()的值为HashMap的key
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
}
CopyOnWriteArraySet线程安全,底层使用的是CopyOnWriteArraySet
public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements java.io.Serializable {
private static final long serialVersionUID = 5457747651344034263L;
private final CopyOnWriteArrayList<E> al;
// 构造方法new了一个CopyOnWriteArrayList
public CopyOnWriteArraySet() {
al = new CopyOnWriteArrayList<E>();
}
public boolean add(E e) {
return al.addIfAbsent(e);
}
}