Before writingCodeEncountered a concurrentmodificationexception. Baidu found that it was caused by the use of iterator to change the original data.
The business requirements are as follows:
There is a data listener list. When the system receives the data, it traverses each item in the list and sends the data. The listener can be added or deleted during traversal.
In this case, you can use copyonwritearraylist to implement the listener list.
The principle is as follows:
Moving a reference from an object to another object in Java does not require CPU time. It can be considered as an atomic operation.
In Java, if an object still has a reference, it will not be recycled by CG.
Copyonwritearraylist is based on the above two features, when the list has been updated, directly copy the original list, and then update the new list, after that, move the reference to the new list. If the old list is still in use (for example, traversing), it will continue to be valid. In this way, there will be no changes to the objects in use (read and write occur on two objects respectively), and the read operation does not have to wait for the completion of the write operation, this removes the need to use locks to speed up reading.
In addition, copyonwritearraylist needs to copy the entire array during writing. Therefore, this operation is time-consuming and is not suitable for businesses with frequent writing.