JUC-List
2020-02-25 本文已影响0人
GIT提交不上
ArrayList构造函数:构造一个初始容量为10的空列表。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
ArrayList是线程不安全的,add方法未加锁,会发生java.util.ConcurrentModificationException(并发修改异常),并发争抢修改导致。分析思路:故障现象->导致原因->解决方案->优化建议。
解决方法:
- Vector
- Collections.synchronizedList()
- CopyOnWriteArrayList(采用)
/**
* @author luffy
**/
public class ArrayListDemo {
public static void main(String[] args){
//List<String> list = new ArrayList<>();
List<String> list = new CopyOnWriteArrayList<>();
//java.util.ConcurrentModificationException-并发修改异常
//1、Vector add方法加锁-但性能急剧下降
//2、List<String> list = Collections.synchronizedList(new ArrayList<>());
//3、CopyOnWriteArrayList-写时复制List
/**
* 故障现象-导致原因-解决方案-优化建议
*/
for(int i =0 ;i< 30;i++){
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,10));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
CopyOnWriteArrayList类add方法源码(写时复制思想,读写分离):
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
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();
}
}