ConcurrentModificationException java appear in the causes, solutions and other

JAVA development sometimes ConcurrentModificationException, the anomaly is due to the traversal Collection made a deletion or addition of operations, this time the size of the original statistics and the new size is not uniform, resulting in the exception. The following is an explanation on StackOverflow:
[quote]

Here apos Why: of As IT IS (Pic) in The the Javadoc:
of The iterators returned by the this class apos Iterator and listIterator Methods are Fail-FAST: IF The List IS structurally Modified AT the any Time After The Iterator IS Created , in any way except through the iterator 's own remove or add methods, the iterator will throw a ConcurrentModificationException.

This check is done in the next() method of the iterator (as you can see by the stacktrace). But we will reach the next() method only if hasNext() delivered true, which is what is called by the for each to check if the boundary is met. In your remove method, when hasNext() checks if it needs to return another element, it will see that it returned two elements, and now after one element was removed the list only contains two elements. So all is peachy and we are done with iterating. The check for concurrent modifications does not occur, as this is done in the next() method which is never called.

Next we get to the second loop. After we remove the second number the hasNext method will check again if can return more values. It has returned two values already, but the list now only contains one. But the code here is:

public Boolean the hasNext () {
return Cursor = size ();!
}

!. 1 = 2, SO WE Continue to The Next () Method, Which now realizes that that someone has been Messing with The List and Fires The Exception.

Hope that Clears your question up. [/ quote]

to solve this problem, there are many online articles. Most talk about is traversing Collection in a thread, while the delete operation, it is recommended to use Iterator # remove () method, rather than its remove (Obj) method. But if it is the case of multi-threaded, even if a thread is used in Iterator # remove () method has changed a Collection, while another thread is traversing the Collection, or will have the same problem.
So the solution is the need to use two threads to the Collection places that are locked, you can lock Collection, or the Collection class contains locked.

And to solve the case while traversing the increase of List can be changed CopyOnWriteArrayList, Map replaced by the corresponding synchronous version can ConcurrentHashMap.
Published 56 original articles · won praise 0 · Views 7774

Guess you like

Origin blog.csdn.net/chainhou/article/details/84472200