java - Populate a thread-safe Set concurrently -


assuming have thread-safe collection, populate in following manner:

   set set = new hashset();    (map map : maps) {         set.addall(dosomeexpensiveprocessing(map.keyset()));     } 

what best way of performing concurrently? (ie each map concurrently add keys set.

edit - i'm aware hashset not thread-safe, outside scope of question, far i'm concerned.

edit2 - correctly pointed particular scenario concurrency not reap huge benefits, there additional steps, i've included in code example.

while @oldcurmudgeon has nice basic approach, in more serious code want make callable expensive processing of keys, , returns new collection. can combined executor and/or completionservice. don't need concurrent collection @ end.

e.g., if keys strings

public class doesexpensiveprocessing implements callable<set<string>> {     final set<string> inkeys;     public doesexpensiveprocessing(set<string> keys) {      this.inkeys = keys;  // make defensive copy if required...    }     public set<string> call() {       // expensive processing on inkeys , returns set of strings    } } 

at point don't need parallel collection

list<doesexpensiveprocessing> doinparallel = new arraylist<doesexpensiveprocessing>(); (map map : maps) {    doinparallel.add(new doesexpensiveprocessing(map.keyset())); }  set theresultingset = new hashset<string>(); list<future<set<string>>> futures = someexecutorservice.invokeall(doinparallel); (future<set<string>> f : futures) {   theresultingset.addall(f.get()); } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -