Fast failure is an error detection mechanism for Java collections. When multiple threads perform structural changes to the collection, a fail-fast mechanism may occur.
For example: Suppose there are two threads (thread 1, thread 2), thread 1 traverses the elements in set A through Iterator, and at some point thread 2 modifies the structure of set A (it is a modification of the structure, not a simple Modify the content of the collection element), then the program will throw ConcurrentModificationException at this time, resulting in a fail-fast mechanism.
Reason: The iterator directly accesses the contents of the collection during traversal, and uses a modCount variable during the traversal. If the content of the collection changes during the traversal, it will change the value of modCount. Whenever the iterator uses hashNext()/next() to traverse the next element, it will check whether the modCount variable is the expectedmodCount value, and if so, return to the traversal; otherwise, throw an exception and terminate the traversal.
Solution:
- In the traversal process, all the places involved in changing the modCount value are all added synchronized.
- Use CopyOnWriteArrayList to replace ArrayList
- Use the Collections. unmodifiableCollection(Collection c) method to create a read-only collection, so that any operation that changes the collection will throw a Java. lang. UnsupportedOperationException. The sample code is as follows:
List<String> list = new ArrayList<>();
list. add("x");
Collection<String> clist = Collections. unmodifiableCollection(list);
clist. add("y"); // 运行时此行报错
System. out. println(list. size());