public class NoSafeList {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
for (int i = 0; i < 15; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
//java.util.ConcurrentModificationException并发异常
}
}
故障现象
1.java.util.ConcurrentModificationException并发异常
2.集合中有元素为null
[null, 5c054, a19b1]
[null, 5c054, a19b1, 6c39a, 97d34]
[null, 5c054, a19b1, 6c39a]
[null, 5c054, a19b1]
[null, 5c054, a19b1]
导致原因
并发争抢修改
解决方案
1.使用Vector实现类
List<String> list=new Vector<>();
2.使用Collections工具类
List<String> list=Collections.synchronizedList(new ArrayList<>());
3.使用CopyOnWriteArrayLit()
List<String> list=new CopyOnWriteArrayList<>();
//源码
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();
}
}
解决方案
1.使用Collections工具类
Set<Object> set2 = Collections.synchronizedSet(new HashSet<>());
2.使用CopyOnWriteArraySet()
Set<Object> set1 = new CopyOnWriteArraySet<>(new HashSet<>());
解决方案
1.使用Collections工具类
Map<Object, Object> map = Collections.synchronizedMap(new HashMap<>());
2.使用ConcurrentHashMap()
ConcurrentMap<Object, Object> map1 = new ConcurrentHashMap<>();
写时复制技术,从读写分离的角度去保证了线程的安全性
ReentrantLock
上锁,与其他线程的写操作互斥public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//获取原数组
Object[] elements = getArray();
//记录长度
int len = elements.length;
//复制原数组 ,长度+1
Object[] newElements = Arrays.copyOf(elements, len + 1);
//写入
newElements[len] = e;
//设置为新数组
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}