I have one situation in a multi-threaded environment where there is no logical problem, but it bothers me if the java Set iterator can break in some corner case. I do not know if this can happen after a while or not:
class Bar{
AtomicLong a = 0;
AtomicLong b = 0;
public void addA(int value){
a.addAndGet(value);
}
public void addB(int value){
b.addAndGet(value);
}
}
class Foo{
Set<Bar> bars = new CopyOnWriteArraySet();
public void addBarData(Bar bar){
if (!bars.add(bar)){
for (Bar b: bars){
if (bar.equals(b)){
b.addA(bar.a);
b.addB(bar.b);
}
}
}
}
}
The problem may be that two threads call addBarData (barInstance) in the near future, one enters the ifs body and starts an iteration for each, but the other adds another element to the set at that moment. Will the for loop (or iterator) replace it due to a change in the number of elements or not?
source
share