2014-09-27 24 views
6

我編寫了一個基於隨機性生成迷宮的函數。大多數情況下,這個功能非常快。但每隔一段時間,由於隨機數字運氣不好,需要幾秒鐘的時間。並行執行競爭性計算並丟棄除第一個完成的所有條目外

我想多次平行啓動這個函數,讓最快的函數「win」。

Scala標準庫(或Java標準庫)是否爲這項工作提供了合適的工具?

+3

可能更容易(和更有效)找出爲什麼程序有時需要幾秒鐘的時間解決它...... – immibis 2014-09-27 11:35:14

+0

您可能希望[ExecutorCompletionService(http://docs.oracle .com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html),但我同意@immibis – hsluo 2014-09-27 11:55:56

+0

@immibis似乎迷宮一代(沒有死路一條)只是一個難題,每個解決方案我發現/可以想到需要大量的回溯。 – fredoverflow 2014-09-27 12:00:03

回答

1

一個java 8溶液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 5,6,7解決方案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(); 
    } 
} 
+0

這聽起來像一個完美的機會使用CompletionFuture與acceptEither CompletionStage。 – TechTrip 2014-09-27 12:29:17

5

您可以使用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) 

如果你想阻止(我想你這樣做),你可以使用Await.result

import scala.concurrent.Await 
import scala.concurrent.duration.Duration 

val result = Await.result(resultFuture, Duration.Inf) 
+0

當第一次計算完成時,是否有一種簡單的方法可以取消待定計算? – fredoverflow 2014-09-27 23:28:15

+0

@FredOverflow看到這個問題:http://stackoverflow.com/questions/16009837/how-to-cancel-future-in-scala – rightfold 2014-09-27 23:34:59

相關問題