0

At oldSet.removeAll(deleted); this exception is thrown

ConcurrentModificationException

I add "synchronized" keyword but no change!!

Set<Employees> deleted;

Set<Employees> oldSet = new TreeSet<Employees>(new EmployeeComparator());
oldSet.addAll(employeesListDB);

Set<Employees> newSet = new TreeSet<Employees>(new EmployeeComparator());
newSet.addAll(employeesList);      

 try{      

     deleted = Sets.difference(oldSet, newSet);

    Set<Employees> added = Sets.difference(newSet, oldSet);

    ***oldSet.removeAll(deleted);***
    oldSet.addAll(added);        

}catch(Exception ex){
    System.out.println(ex.getMessage());
}

I also tried the iterator but the same exception appears:

Iterator it = oldSet.iterator();
            Employees e;
            while(it.hasNext())
            {
                e= (Employees)it.next();
                if(oldSet.contains(e))
                    oldSet.iterator().remove();
            }
Mariam A. Moustafa
  • 165
  • 1
  • 2
  • 14
  • This has a solution [here](http://stackoverflow.com/questions/1496180/concurrent-modification-exception). – Uma Kanth Jun 17 '15 at 13:17
  • nope, it doesn't solve my problem, I am using Set not List! – Mariam A. Moustafa Jun 17 '15 at 13:24
  • Using an iterator is the key for it. – Uma Kanth Jun 17 '15 at 13:25
  • 1
    I think the problem here is with wrong usage of the Google Collections API. Assuming you are using `Sets` of the Google collections API, the problem is that `Sets.difference` returns a view backed by the original sets. Now when you're calling `removeAll` you iterate over `oldSet` while (concurrently) modifying it. Using `immutableCopy` should do the trick. `deleted = Sets.difference(oldSet, newSet).immutableCopy();` – Michael Lang Jun 17 '15 at 13:26
  • 1
    Actual duplicate should be this one: http://stackoverflow.com/questions/8490901/com-google-common-collect-sets-setview-bug-or-feature – Michael Lang Jun 17 '15 at 13:29
  • Yes @michaelLang ....immutableCopy(); solves my problem ... many thanks – Mariam A. Moustafa Jun 17 '15 at 13:32
  • Here is the answer: http://stackoverflow.com/questions/8490901/com-google-common-collect-sets-setview-bug-or-feature – Mariam A. Moustafa Jun 17 '15 at 13:34

1 Answers1

2

The ConcurrentModificationException is not linked to a synchronization (multithread) problem.

From javadoc: This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.... Note that this exception does not always indicate that an object has been concurrently modified by a different thread...

It happens for example if you iterate over a Collection (using iterator) and you change the Collection at the same time (adding or removing elements for example).

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56