文章同步更新在个人公众号“梓莘”,欢迎大家关注,相互交流。
写时复制:CopyOnWriteArrayList
CopyOnWrite容器即写时复制的容器,往一个容器添加元素的时候,不直接往当前容器Object[]添加,而是先将当前容器Object[]进行Copy,复制出一个新的容器Object[] newElements,然后新的容器Object[] newElwmwnts里添加元素,添加元素之后,再将原容器的引用指向新的容器setArrat(newElements);这样做的好处是可以CopyOnWrite容器进行并发的读,而不需要加锁,因为当前容器不会添加任何元素。
所以CopyOnWrite容器也是一种读写分离的思想,读和写不同的容器。
案例
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、故障现象:java.util.ConcurrentModificationException
* 2、导致原因
* 并发争抢修改导致,一个线程正在写,另外一个线程过来抢夺,导致数据不一致,出现数据修改异常
* 3、解决方法
* 3.1、使用Vector(Vector出现在ArrayList之前)
* 3.2、Collections.synchronizedList(new ArrayList<String>());
* 3.3、new CopyOnWriteArrayList<String>();
* 4、优化建议
*/
Collections.synchronizedList(new ArrayList<String>());
new CopyOnWriteArrayList<String>();
}
}
- ArrayList实现
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参数只有一个而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;
}
网友评论