package mho.wheels.concurrency;

import mho.wheels.structures.Pair;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

import static mho.wheels.iterables.IterableUtils.*;

public class ConcurrencyUtils {
    public static @NotNull <A, B> Pair<String, B> evaluateFastest(
            @NotNull Map<String, Function<A, B>> functions,
            A input
    ) {
        ExecutorService service = Executors.newFixedThreadPool(functions.size());
        List<Callable<Pair<String, B>>> tasks = toList(
                map(p -> (() -> new Pair<>(p.a, p.b.apply(input))), fromMap(functions))
        );
        try {
            return service.invokeAny(tasks);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException ignored) {
            throw new IllegalArgumentException();
        } finally {
            service.shutdownNow();
        }
    }
}

@@ -181,148 +181,9 @@
 ent.
-Callable;%0Aimport java.util.concurrent.ExecutionException;%0Aimport java.util.concurrent.ExecutorService;%0Aimport java.util.concurrent.Executors
+*
 ;%0Aim
@@ -694,16 +694,48 @@
      );%0A
+        Pair%3CString, B%3E result;%0A
         
@@ -758,12 +758,14 @@
   re
-turn
+sult =
  ser
@@ -983,63 +983,221 @@
    %7D
- finally %7B%0A            service.shutdownNow();%0A        %7D
+%0A        service.shutdownNow();%0A        try %7B%0A            service.awaitTermination(1, TimeUnit.MINUTES);%0A        %7D catch (InterruptedException e) %7B%0A            e.printStackTrace();%0A        %7D%0A        return result;
 %0A   

change evaluateFastest implementation