[英]CompletableFuture : java.util.concurrent.TimeoutException
I am working on a use-case where 5 external tasks needs to be computed and then aggregated together.我正在研究一个需要计算 5 个外部任务然后聚合在一起的用例。 If all tasks do not complete within 3 secs, then return with completed tasks.如果所有任务都没有在 3 秒内完成,则返回已完成的任务。
private Set<Double> getPrices() throws ExecutionException, InterruptedException, TimeoutException {
Set<Double> prices=new CopyOnWriteArraySet<>(); // Concurrent Set
//5 independant Tasks
CompletableFuture<Void> d1= CompletableFuture.runAsync(new Task("1", prices))
.thenRunAsync(new Task("2", prices))
.thenRunAsync(new Task("3", prices))
.thenRunAsync(new Task("4", prices))
.thenRunAsync(new Task("5", prices));
d1.get(3,TimeUnit.SECONDS);
return prices;
}
The run method in class:Task calls external system to retrieve result. class 中的运行方法:任务调用外部系统检索结果。 For simplicity, return a random price(1-00)为简单起见,返回一个随机价格(1-00)
class Task{
private String id; //Task-ID
private Set<Double> prices;
public Task(String id,Set<Double> prices){
this.id=id;
this.prices=prices;
}
@Override
public void run() {
try {
Thread.sleep(1500); //Adding delay to simulate external call
double d =Math.random*100;//Calling external System
prices.add(d);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
When I call the getPrice method, get java.util.concurrent.TimeoutException当我调用 getPrice 方法时,得到 java.util.concurrent.TimeoutException
public static void main(String args []) throws InterruptedException,
ExecutionException, TimeoutException {
PriceComparatorAggregator p2=new PriceComparatorAggregator();
outputPrices = p2.usingCompletableFuture();
for(Double d:outputPrices)
System.out.println(d);
System.out.println("Complete..!!");
}
You are running these tasks in a sequence (one task starts after the previous completes), it will take more than 3 seconds to run all of them.您正在按顺序运行这些任务(一个任务在前一个任务完成后开始),运行所有这些任务需要 3 秒以上。
I think you want to run them in parallel.我想你想并行运行它们。 This is one way you could do it:这是您可以做到的一种方法:
public static Set<Double> getPrices() throws Exception {
Set<Double> prices = new CopyOnWriteArraySet<>(); // Concurrent Set
CompletableFuture<Void>[] tasks = new CompletableFuture[5];
for ( int i = 0; i < tasks.length; i++ ) {
// Create a new task and run it
tasks[i] = CompletableFuture.runAsync( new Task( String.valueOf( i + 1 ), prices ) );
}
// Wait for all the tasks to complete
CompletableFuture.allOf( tasks ).get( 3, TimeUnit.SECONDS );
return prices;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.