Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent iteration and deletion from Set in Java

I have a pre-populated set of strings. I want to iterate over the items and while iterating, i need to "do work" which might also remove the item from the set. I want to spawn a new thread for each item's "do work". Please note that only some items are removed from the set during "do work".

Now i have the following question,

Can i achieve this by simply using Collections.synchronizedSet(new HashSet()); ? I am guessing this will throw up ConcurrentModificationException since i am removing items from the list while i am iterating. How can i achieve the above behavior efficiently without consistency issues ?

Thanks!

like image 631
shadowfax Avatar asked Mar 23 '26 09:03

shadowfax


1 Answers

I would use an ExecutorService

ExecutorService es = Executors.newFixedThreadPool(n);
List<Future<String>> toRemove = new ARraysList<>();
for(String s: set)
   toRemove.add(es.submit(new Task(s)));
for(Future<String> future : toRemove()) {
   String s = future.get();
   if (s != null)
       set.remove(s);
}

This avoids needing to access the collection in a multi-threaded way.

like image 85
Peter Lawrey Avatar answered Mar 24 '26 21:03

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!