List不安全
//ArrayList扩容源码
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public class ListTest {
public static void main(String[] args) {
/* 单线程安全
List<String> list = Arrays.asList("1", "2", "3");
list.forEach(System.out::println);*/
//并发下ArrayList @since 1.2 是不安全的
/*
* 解决方案:1. Vector @since JDK1.0
* 2. Collections.synchronizedList(new ArrayList<>()); (利用工具类Collections转化为安全)
* 3. new CopyOnWriteArrayList<>();(利用juc包下的类) (private transient volatile Object[] array;)*/
//CopyOnWriteArrayList写入时复制 COW计算机程序设计领域的一种优化策略
//多个线程调用的时候,list,读取的时候固定的,写入的时候 覆盖
//在写入的时候避免覆盖造成数据问题
//读写分离 Mycat
//CopyOnWriteArrayList比vector好在哪里?性能更高(vector使用synchronized,而CopyOnWriteArrayList使用Lock锁)
List<String> list=new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
/*报错:并发修改异常
* Exception in thread "2" Exception in thread "0" Exception in thread "3" Exception in thread "6" java.util.ConcurrentModificationException*/
},String.valueOf(i)).start();
}
}
}
Set不安全
public class SetTest {
/*
* 同理可证 ConcurrentModificationException
* 解决方案
* 1. 利用Collections工具类转为安全类型
* 2. CopyOnWriteArraySet<E>
*
* #HashSet的底层是什么?
* 就是HashMap*/
public static void main(String[] args) {
Set<String> set=new CopyOnWriteArraySet<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
/*报错:并发修改异常
* Exception in thread "5" Exception in thread "8" java.util.ConcurrentModificationException*/
},String.valueOf(i)).start();
}
}
}
HashSet底层
Map不安全
public class MapTest {
public static void main(String[] args) {
//工作中不适用HashMap
//默认等价于
// Map<String,String> map=new HashMap<>(16, 0.75f);
/*
加载因子以及初始化容量
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}*/
/*
* 解决方案
* 1. 利用Collections工具类转为安全类型
* 2. ConCurrentHashMap*/
Map<String,String> map=new ConcurrentHashMap<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
/*报错:并发修改异常
* Exception in thread "0" Exception in thread "9" Exception in thread "1" Exception in thread "6" java.util.ConcurrentModificationException*/
},String.valueOf(i)).start();
}
}
}