Java – why doesn’t ArrayList throw a concurrentmodificationexception when modifying from multiple threads?
Concurrent modificationexception: when such modification is not allowed, the method that detects concurrent modification of the object may throw this exception
The above is the definition of concurrentmodificationexception from Javadoc
So I try to test the following code:
final List<String> tickets = new ArrayList<String>(100000); for (int i = 0; i < 100000; i++) { tickets.add("ticket NO," + i); } for (int i = 0; i < 10; i++) { Thread salethread = new Thread() { public void run() { while (tickets.size() > 0) { tickets.remove(0); System.out.println(Thread.currentThread().getId()+"Remove 0"); } } }; salethread.start(); }
The code is simple Ten threads delete elements from ArrayList objects Ensure that multiple threads access an object But it works normally No exceptions were thrown Why?
Solution
For your benefit, I quote most of the contents of ArrayList Javadoc The relevant section explaining the behavior you see will be highlighted
ArrayLists usually throw concurrent modification exceptions if the list is structurally modified when accessed through an iterator (although this is not an absolute guarantee) Note that in your example, you will delete the element directly from the list, and you do not use an iterator
If it interests you, you can also browse ArrayList The implementation of remove to better understand its working principle