Search code examples
javamultithreadingconcurrencyconcurrentmodification

how to Continous loop collection without concurrentmodificationexception


Please read the text carefully, the title isn't so good, but i couldn't think something easier to describe the problem.

This is a theorical problem, i will use java to demonstrate but the solution i need is more like a design pattern so it could be thougth for any language.

A program has 2 threads:
thread A - interacts with user, who can add or remove items to a set
thread B - continously iterate over a Set performing tasks over its items

How can i perform this scenario without having ConcurrentModificationException ?

final Set<String> set = new HashSet();

//A
new Thread(new Runnable(){
public void run(){
while(true){

//user adds or remove items to set

}
}
}).start();


new Thread(new Runnable(){
public void run(){
while(true){

for(String s : set){
//do stuff
}

}
}
}).start();

This is a very commum scenario there shall be a design pattern to handle it


Solution

  • You could use CopyOnWriteArraySet

    For example

    Set<Integer> threadSafeSet = new CopyOnWriteArraySet<>();

    The above set can now be accessed from any thread without ConcurrentModificationExceptions. But its not realtime i.e the set can change and this wont be reflected in an ongoing iteration. This a drawback for the benefit of a thread safe iterator