線程安全的Set
J.U.C中實(shí)現(xiàn)Set接口的并發(fā)容器有CopyOnWriteArraySet和ConcurrentSkipListSet。
可以通過(guò)Collections.synchronizedSet(Set)構(gòu)造一個(gè)線程安全的Set,同樣使用synchronized進(jìn)行串行化,吞吐量不高。
可以通過(guò)Collections.newSetFromMap(ConcurrentHashMap)來(lái)構(gòu)建,使用ConcurrentHashMap保證并發(fā)性,因此性能較高。
CopyOnWriteArraySet
內(nèi)部維護(hù)一個(gè)CopyOnWriteArrayList實(shí)例,所有的方法都是委托給這個(gè)實(shí)例實(shí)現(xiàn),添加方法調(diào)用的是addIfAbsent以保證無(wú)重復(fù)數(shù)據(jù)。
ConcurrentSkipListSet
內(nèi)部維護(hù)一個(gè)ConcurrentSkipListMap實(shí)例,所有的方法都是委托給這個(gè)實(shí)例實(shí)現(xiàn)。
添加操作:
public boolean add(E e) {
return m.putIfAbsent(e, Boolean.TRUE) == null;
}
調(diào)用putIfAbsent保證元素不重復(fù),鍵為元素e,值為Boolean.TRUE。
SetFromMap
Collections的內(nèi)部類,使用包裝的Map.keySet()作為容器
private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable{
private final Map<E, Boolean> m; // The backing map
private transient Set<E> s; // Its keySet
SetFromMap(Map<E, Boolean> map) {
if (!map.isEmpty()) throw new IllegalArgumentException("Map is non-empty");
m = map;
s = map.keySet();
}
// .... ...
}
碼字不易,轉(zhuǎn)載請(qǐng)保留原文連接http://www.lxweimin.com/p/f25d9d7fdaf3