I get an error on the following line. I'm doing the process of adding to the jsonarray. Please help me.
jsonArr=new JSONArray();
if(req.getSession().getAttribute("userses")!=null){
String name=(req.getParameter("name")==null?"":to_EnglishName(req.getParameter("name").toUpperCase()));
if(!name.equals("")){
for(Book c:GlobalObjects.bookList){
if(c.getBookName().startsWith(name)){
jsonObjec=new JSONObject();
jsonObjec.put("label",c.getBookName());
jsonObjec.put("value", c.getId());
jsonArr.add(jsonObjec);//java.util.ConcurrentModificationException
}
}
}
}
jsonArr.write(res.getWriter());
Also one more way is there, ie insted of passing actual list , we can pass clone of list for iteration.
listForIteration = list.clone();
//Do operation..
This is an error I often met while reprogramming. the reason or detail of this exception are pretty clear. it is unallowed to modify the collection(you are adding a new element) while it is being iterated. At least the syntax
for
DO NOT support do that.To fix your problem, there have two way I think it is simple.
1). rather than using
for
statement to loop over, the better way is to use iterator to avoid ConcurrentModificationException.2). while looping it, don't add it.
You get ConcurrentModificationException when you are iterating over a collection and you modify the same collection within the loop. The given code snippet does not show that, so there is something else above or below modifying the collection. Try declaring the jsonArr right at the place where you instantiate it.
One possible reason could be the jsonArr instance Object is class level and is accessed by multiple threads. Declare the jsonArr object where it is instantiated.
Edit: Make jsonArr a local variable.
Or use a ListIterator which allows iterating and modifying the same list
http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html
just use
java.util.concurrent.CopyOnWriteArrayList
To fix this problem, make sure that
If your collection is not thread safe then it must not get modified with another thread when some other thread is iterating over this collection
.There are two possible ways to fix this problem -
1) One solution is to synchronize all access to the collection
2) Use Thread safe collection like
CopyOnWriteArrayList
From Java Doc -