ArrayList -> CopyOnWriteArrayList
當(dāng)有新元素添加到CopyOnWriteArrayList的時(shí)候,先從原有的數(shù)組里拷貝一份出來(lái)肘习,然后在新的數(shù)組上做些操作,寫完之后再將原來(lái)的數(shù)組指向新的數(shù)組 裹匙。整個(gè)的add操作都是在寫的保護(hù)下進(jìn)行的讼昆,避免在多線程并發(fā)下進(jìn)行add操作時(shí)復(fù)制出多個(gè)數(shù)組出來(lái)腕巡,把數(shù)據(jù)搞亂
缺點(diǎn):消耗內(nèi)存; 不能用于實(shí)時(shí)讀的操作
適合讀多寫少的場(chǎng)景
設(shè)計(jì)思想:讀寫分離、最終結(jié)果一致性
讀操作時(shí)在原數(shù)組上進(jìn)行嫩挤,不需要加鎖害幅,寫操作時(shí)加鎖
add操作加鎖源碼
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
synchronized (lock) {
Object[] elements = getArray();
int len = elements.length;
if (index > len || index < 0)
throw new IndexOutOfBoundsException(outOfBounds(index, len));
Object[] newElements;
int numMoved = len - index;
if (numMoved == 0)
newElements = Arrays.copyOf(elements, len + 1);
else {
newElements = new Object[len + 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index, newElements, index + 1,
numMoved);
}
newElements[index] = element;
setArray(newElements);
}
}
get不加鎖源碼
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return elementAt(getArray(), index);
}
HashSet -> CopyOnWriteArraySet
線程安全的,底層實(shí)現(xiàn)是用到了CopyOnWriteArrayList
岂昭,適合于大小較小的list集合以现,只讀大于寫操作的場(chǎng)景,因?yàn)樾枰獜?fù)制整個(gè)數(shù)組,所以開銷邑遏,迭代器不支持remove操作
TreeSet -> ConcurrentSkipListSet
支持自然排序佣赖,基于Map集合,多個(gè)線程可以并發(fā)執(zhí)行add,remove等操作无宿,但是對(duì)于批量操作如addAll,removeAll等不能保證以原子方式執(zhí)行因?yàn)榈讓舆€是調(diào)用單次的add等操作茵汰,只能保證每一次的操作是原子性的,批量操作需要手動(dòng)加鎖
HashMap -> ConcurrentHashMap
TreeMap -> ConcurrentSkipListMap
key有序孽鸡,支持更高的并發(fā)