Java – list concurrentmodificationexception

I have the following code

public void saveProjects(List<Project> proj) throws DatabaseException {
    for (Project listItems: proj) { // error here

        insertProjects(listItems);
    }
}

private void insertProjects(Project prj) throws DatabaseException {
    commitObjects(prj);
}

When I execute the above operation, I get the following exception (project listitems: proj){

How can I use next or with iterator to solve this problem?

Edit 1

I'm calling a snippet of saveprojects

projectList.add(proj);
  for (Project persist: projectList) {
       persist.setProjectId("K7890");
       persist.setName(fileName);

          myDAO.saveProjects(projectList);

     }
  projectList.clear();

Solution

From code

for (Project persist: projectList) { 
     persist.setProjectId("K7890");
     persist.setName(fileName);

      myDAO.saveProjects(projectList); 
 }

projectList.clear(); // <-- clear might cause to this Exception

reference resources

Why does concurrentmodificationexception occur when using iterators?

java. The util collection class fails quickly, which means that if one thread changes the collection and another thread uses an iterator to traverse it, the iterator Hasnext() or iterator The next () call will throw a concurrentmodificationexception

Even synchronized collection wrapper classes synchronizedmap and synchronizedlist are only conditionally thread safe, which means that all individual operations are thread safe, but composite operations, in which the control flow depends on the results of previous operations, may be affected by thread problems (mylist = collections. Synchronizedlist (mylist)! (this may not work)

Solutions for multithreaded access

Solution 1: you can use list Toarray() converts the list to an array and iterates over the algebraic group This method is not recommended if the list is large

Solution 2: you can lock the entire list during iteration by wrapping the code in a synchronization block If the application is highly concurrent, this method will have a negative impact on the scalability of the application

Solution 3: you can use the concurrenthashmap and copyonwritearraylist classes, which provide better scalability, concurrenthashmap The iterator returned by iterator () will not throw a concurrentmodificationexception while preserving thread safety

Solution for single thread access

use:

it.remove();

It deletes the current object through the iterator, which has a reference to the underlying collection list

Avoid:

list.remove(myObject);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>