1

I would like to refactor the following code

Set<String> allStrings ...
Set<MyTask> myTasks = ...
myTasks.add(new MyTask());
myTasks.add(new MyTask());
...
List<Future<Set<String>>> futures = executorService.invokeAll(myTasks);
executorService.shutdown();
for (Future<Set<String>> future : futures) {
    Set<String> strings = future.get();
    allStrings.addAll(strings);
}
// do stuff with allStrings
....

such that the allStrings is passed to MyTask where the variable is populated inside the class and the Future returns Void:

Set<String> allStrings ...
Set<MyTask> myTasks = ...
myTasks.add(new MyTask(allStrings));
myTasks.add(new MyTask(allStrings));
...
executorService.invokeAll(myTasks);
executorService.shutdown(); 
// do stuff with allStrings
....

Is it okay to do so? Is there any concurrency thing that I have to worry about because the results seem to be different (in my actual code - not this code)?

Also, can I assume that all tasks are completed such that I do not have to do a dummy loop before doing stuff with allStrings:

for (Future<Set<String>> future : futures) {
    future.get();
}
// do stuff with `allStrings`

1 Answers1

1

The only thing you should worry here about is concurrent access to this allString collection.

So, depending on what are doing in this threads (in MyTask), you should choose appropriate synchronized implementation of Set; which one, you can read here: Different types of thread-safe Sets in Java

Community
  • 1
  • 1
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • @Andemoniy Supposed all I am doing inside `MyTask` is adding to the `allStrings` without removing anything, should synchronization be an issue? –  Jan 09 '16 at 08:05
  • 2
    @FaizalKamarrudin Yes. Adding to a `Set` is a complex operation. If the implementation is a `HashSet`, the adding operation will involve reading a linked list reference from a hash table bucket, and then modifying the list and/or the bucket. If two tasks try to add two objects with the same hash index simultaneously, they will both be trying to update the same linked list at the same time, and the result will be a disaster. – ajb Jan 09 '16 at 08:14
  • @ajb Didn't know that. Thanks. –  Jan 09 '16 at 08:30