When a code segment is enumerating a set and another code segment tries to modify the set, a common multithreading problem occurs. To solve this problem, copy an enumeration variable before processing.
How many times have you encountered the following prompt when writing multi-threaded code:
Exception in thread "main" java. util. ConcurrentModificationException
There are several causes for this exception. The first is to directly call the delete operation on the set instead of on the enumerator. Second, when different threads try to add or delete a set.
The first step of this solution is to synchronize the code so that other threads cannot add or delete records during enumeration. However, if complicated computing or database access is required for each enumeration process, this synchronization will lead to terrible consequences. To reduce the negative impact, you can copy a read-only enumerator, remove synchronization, and use the method shown in the following code:
Private List list;
Public void add (Object obj ){
Synchronized (list ){
List. add (obj );
}
}
Public void perform (){
Iterator iterator = null;
Synchronized (list ){
Iterator = new CopiedIterator (list. iterator ());
}
While (iterator. hasNext ()){
// Perform resource or cpu hungry work
}
}
It is important to remember that CopiedIterator is not a clone, but a read-only copy, so it does not maintain all the original functions. The most important thing is that you cannot call CopiedIterator. remove. The implementation of CopiedIterator. remove is as follows:
Public class CopiedIterator implements Iterator {
Private Iterator iterator = null;
Public CopiedIterator (Iterator itr ){
Jsonlist list = new jsonlist ();
While (itr. hasNext ()){
List. add (itr. next ());
}
This. iterator = list. iterator ();
}
Public boolean hasNext (){
Return this. iterator. hasNext ();
}
Public void remove (){
Throw new UnsupportedOperationException ("This is a read-only iterator.
");
}
Public Object next (){
Return this. iterator. next ();
}
}
The read-only copy of the enumerator will reduce the time used for synchronization to a minimum, so the global efficiency can be enhanced.