ArrayList 线程不安全的案例和解决方案
-
故障现象
public class ContainerDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 100; i++) { new Thread(() -> { list.add(random.nextInt(10)); System.out.println(list); }).start(); } } }
发现报
java.util.ConcurrentModificationException
-
导致原因
- 并发修改导致的异常
-
解决方案
-
new Vector();
-
Collections.synchronizedList(new ArrayList<>());
-
new CopyOnWriteArrayList<>();
-
/** CopyOnWriteArrayList * 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(); } }
-
-
优化建议
- 在读多写少的时候推荐使用 CopeOnWriteArrayList 这个类