-2
Map<String, Map<Long, String>> regions = Service.getWhseByRegions();
for(String region:regions.keySet()){
warehouseList=getAuthorizedWarehouse(dashboardWarhs,regions.get(region));
if(warehouseList!=null && warehouseList.size()>0){
      regions.put(region, warehouseList);
}else{
      regions.remove(region);
}
}

Hi , I am getting ConcurrentModificationException, please help

earthmover
  • 4,395
  • 10
  • 43
  • 74
pnaga
  • 21
  • 1
  • 5
  • @Byakuya no, he's just iterating through a fail-fast key set while modifying it. But seriously, put your question title into google, that immediately gives an answer. – Ordous May 28 '14 at 10:02

3 Answers3

1

You got ConcurrentModificationException, because you remove elements while iterating over collection. Use removeIf() method of Java 8 or safe Iterator#remove() for remove.

earthmover
  • 4,395
  • 10
  • 43
  • 74
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

You are iterating through the Map and trying to modify the same Map. Instead use a temporary duplicate Map for manipulations inside the loop and then assign back to the original Map outside the loop.

Dinal
  • 661
  • 4
  • 9
0

This is a classic error :-) There are two things you should consider

  1. You cannot change the collection that you are currently iterating
  2. There might be more than one thread treating the collection returned by getWhseByRegion()

For the first one: Store all identified items that shall be removed in a different collection instead of removing Iterate over items to be deleted and call remove for each of these items

For the second: Try to protect against concurrent accesses. Most likely you could add something as synchronized to you method or synchonized(lockObjektForWhse) {...}

Seven
  • 4,353
  • 2
  • 27
  • 30