The problem is this. I have made a set
Set<User> users = Collections.synchronizedSet(new HashSet<User>())
...
for(User u : users){
//do something with u
}
Now, according to Java documentation.
It is imperative that the user manually synchronize on the returned sorted set when iterating over it or any of its subSet, headSet, or tailSet views.
SortedSet s = Collections.synchronizedSortedSet(new HashSortedSet()); ... synchronized(s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); }
I'm pretty sure that for each syntax uses iterators but I'm unsure whether or not I should wrap every for each loop with a synchronized block.
Another thing, my IDE (IntelliJ IDEA) keeps reporting that using a synchronized block over a field that is not final is unlikely to have useful semantics since different threads might be different objects, even when working on a same object.