文章同步更新在個(gè)人公眾號(hào)“梓莘”渺杉,歡迎大家關(guān)注蛇数,相互交流。
寫(xiě)時(shí)復(fù)制:CopyOnWriteArrayList
CopyOnWrite容器即寫(xiě)時(shí)復(fù)制的容器是越,往一個(gè)容器添加元素的時(shí)候耳舅,不直接往當(dāng)前容器Object[]添加,而是先將當(dāng)前容器Object[]進(jìn)行Copy,復(fù)制出一個(gè)新的容器Object[] newElements,然后新的容器Object[] newElwmwnts里添加元素倚评,添加元素之后挽放,再將原容器的引用指向新的容器setArrat(newElements);這樣做的好處是可以CopyOnWrite容器進(jìn)行并發(fā)的讀,而不需要加鎖蔓纠,因?yàn)楫?dāng)前容器不會(huì)添加任何元素辑畦。
所以CopyOnWrite容器也是一種讀寫(xiě)分離的思想,讀和寫(xiě)不同的容器腿倚。
案例
package com.zixin;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @ClassName ContainerNotSafeDemo
* @Description TODO
* @Author zixin
* @Date 2019/12/27 12:37
* @Version 1.0
**/
public class ContainerNotSafeDemo {
/**
* HashMap線程不安全
* 解決方案:
* new ConcurrentHashMap<>();
* java.util.ConcurrentModificationException
* @param args
*/
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
new ConcurrentHashMap<>();
for (int i = 0; i <100 ; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
System.out.println(map);
},String.valueOf(i)
).start();
}
}
/**
* HashSet線程不安全
* 解決方案:
* 1.Collections.synchronizedSet(new HashSet<String>())
* 2纯出、new CopyOnWriteArraySet<String>();
* @param args
*/
public static void setNotSafe(String[] args) {
Set<String> set = Collections.synchronizedSet(new HashSet<String>());
new CopyOnWriteArraySet<String>();
for (int i=1;i<=500;i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(set);
},String.valueOf(i)).start();
}
}
public static void listNotSafe(String[] args) {
//Constructs an empty list with an initial capacity of ten.
new ArrayList<Integer>().add(1);
List<String> list = new ArrayList<String>();
for (int i=1;i<=500;i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(list);
},String.valueOf(i)).start();
}
//java.util.ConcurrentModificationException
/**
* 1、故障現(xiàn)象:java.util.ConcurrentModificationException
* 2敷燎、導(dǎo)致原因
* 并發(fā)爭(zhēng)搶修改導(dǎo)致暂筝,一個(gè)線程正在寫(xiě),另外一個(gè)線程過(guò)來(lái)?yè)寠Z硬贯,導(dǎo)致數(shù)據(jù)不一致焕襟,出現(xiàn)數(shù)據(jù)修改異常
* 3、解決方法
* 3.1饭豹、使用Vector(Vector出現(xiàn)在ArrayList之前)
* 3.2鸵赖、Collections.synchronizedList(new ArrayList<String>());
* 3.3、new CopyOnWriteArrayList<String>();
* 4拄衰、優(yōu)化建議
*/
Collections.synchronizedList(new ArrayList<String>());
new CopyOnWriteArrayList<String>();
}
}
- ArrayList實(shí)現(xiàn)
jdk1.9
public boolean add(E e) {
synchronized (lock) {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
}
}
jdk1.8:
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
- HashSet底層是HashMap
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
- set的add參數(shù)只有一個(gè)而map是kV為什么?
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}