Perform parallel parallel computations and drop everything except the first one that ends

I wrote a function that generates a maze based on randomness. Most of the time this function is very fast. But from time to time, due to failure with random numbers, it takes a couple of seconds.

I would like to run this function several times in parallel and allow the fastest win feature.

Does the Scala standard library (or the standard Java library) provide an appropriate tool for this task?

+6
source share
2 answers

Java 8 solution with CompletableFuture :

 public class FirstDoneWithCompletableFutureEx { public static void main(String[] args) throws ExecutionException, InterruptedException { int jobs = 10; CompletableFuture<?>[] futures = new CompletableFuture[jobs]; for (int i = 0; i < jobs; i++) { futures[i] = CompletableFuture.supplyAsync(() -> { //computation return new Object(); }); } //first job done Object firstDone = CompletableFuture.anyOf(futures).get(); } } 

Java solution 5,6,7 with CompletionService :

 public class FirstDoneWithCompletionServiceEx { public static void main(String[] args) throws InterruptedException, ExecutionException { int jobs = 10; ExecutorService executorService = Executors.newFixedThreadPool(jobs); CompletionService<Object> completionService = new ExecutorCompletionService<>(executorService); for (int i = 0; i < jobs; i++) completionService.submit( new Callable<Object>() { @Override public Object call() throws Exception { //computation return new Object(); } } ); //get first job done Object firstDone = completionService.take().get(); executorService.shutdownNow(); } } 
+1
source

You can use Future :

 import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global val futures = for (_ <- 1 to 4) yield Future { /* computation */ } val resultFuture = Future.firstCompletedOf(futures) 

If you want to block (I suppose you do), you can use Await.result :

 import scala.concurrent.Await import scala.concurrent.duration.Duration val result = Await.result(resultFuture, Duration.Inf) 
+5
source

Source: https://habr.com/ru/post/975925/


All Articles