首页 > 解决方案 > 超时不工作的可完成未来

问题描述

我是新的可完成未来。我正在尝试为元素列表(它们是参数)调用并行方法,然后组合结果以创建最终响应。我还尝试设置 50 毫秒的超时,这样如果调用在 50 毫秒内没有返回,我将返回一个默认值。

到目前为止,我已经尝试过:

    {

     List<ItemGroup> result = Collections.synchronizedList(Lists.newArrayList());

    try {
     List<CompletableFuture> completableFutures = response.getItemGroupList().stream()
     .map(inPutItemGroup -> 
       CompletableFuture.runAsync(() -> {
           final ItemGroup itemGroup = getUpdatedItemGroup(inPutItemGroup);               //call which I am tryin to make parallel

           // this is thread safe
           if (null != itemGroup) {
                  result.add(itemGroup); //output of the call
           }
        }, executorService).acceptEither(timeoutAfter(50, TimeUnit.MILLISECONDS),inPutItemGroup))  //this line throws error     
     .collect(Collectors.toList());

// this will wait till all threads are completed
    CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]))
                        .join();
} catch (final Throwable t) {
     final String errorMsg = String.format("Exception occurred while rexecuting parallel call");
                log.error(errorMsg, e);
                result = response.getItemGroupList(); //default value - return the input value if error
    }

    Response finalResponse = Response.builder()
                    .itemGroupList(result)
                    .build();

    }

     private <T> CompletableFuture<T> timeoutAfter(final long timeout, final TimeUnit unit) {
            CompletableFuture<T> result = new CompletableFuture<T>();

            //Threadpool with 1 thread for scheduling a future that completes after a timeout
            ScheduledExecutorService delayer = Executors.newScheduledThreadPool(1);
            String message = String.format("Process timed out after %s %s", timeout, unit.name().toLowerCase());
            delayer.schedule(() -> result.completeExceptionally(new TimeoutException(message)), timeout, unit);
            return result;
     }

但我不断收到错误消息:

 error: incompatible types: ItemGroup cannot be converted to Consumer<? super Void>
    [javac]                             itemGroup))

incompatible types: inference variable T has incompatible bounds
    [javac]                     .collect(Collectors.toList());
    [javac]                             ^
    [javac]     equality constraints: CompletableFuture
    [javac]     lower bounds: Object
    [javac]   where T is a type-variable:

有人可以告诉我我在这里做错了什么吗?如果我走错了方向,请纠正我。

谢谢。

标签: javamultithreadingjava-8executorservicecompletable-future

解决方案


代替

acceptEither(timeoutAfter(50, TimeUnit.MILLISECONDS), inPutItemGroup))

你需要

applyToEither(timeoutAfter(50, TimeUnit.MILLISECONDS), x -> inPutItemGroup)

编译代码。“accept”是一个消耗一个值而不返回一个新值的动作,“apply”是一个产生一个新值的动作。

但是,仍然存在逻辑错误。返回的 futuretimeoutAfter异常完成,因此依赖阶段也将异常完成,无需评估函数,因此这种链接方法不适合用默认值替换异常。

更糟糕的是,修复此问题将创建一个新的未来,该未来由任一源未来完成,但这不会影响result.add(itemGroup)在其中一个源未来中执行的操作。在您的代码中,生成的未来仅用于等待完成,而不用于评估结果。因此,当您的超时时间过去时,您将停止等待完成,而仍然可能有后台线程修改列表。

正确的逻辑是将获取值的步骤(可以在超时时被默认值取代)和将结果(获取的值或默认值)添加到结果列表的步骤分开。然后,您可以等待所有add操作完成。超时时,可能仍在进行getUpdatedItemGroup评估(无法停止执行),但其结果将被忽略,因此不会影响结果列表。

还值得指出的是,ScheduledExecutorService为每个列表元素创建一个新元素(使用后不会关闭,更糟糕的是),这不是正确的方法。

// result must be effectively final
List<ItemGroup> result = Collections.synchronizedList(new ArrayList<>());
List<ItemGroup> endResult = result;
ScheduledExecutorService delayer = Executors.newScheduledThreadPool(1);
try {
    CompletableFuture<?>[] completableFutures = response.getItemGroupList().stream()
    .map(inPutItemGroup ->
        timeoutAfter(delayer, 50, TimeUnit.MILLISECONDS,
            CompletableFuture.supplyAsync(
                () -> getUpdatedItemGroup(inPutItemGroup), executorService),
            inPutItemGroup)
         .thenAccept(itemGroup -> {
            // this is thread safe, but questionable,
            // e.g. the result list order is not maintained
            if(null != itemGroup) result.add(itemGroup);
         })
    )
    .toArray(CompletableFuture<?>[]::new);

    // this will wait till all threads are completed
    CompletableFuture.allOf(completableFutures).join();
} catch(final Throwable t) {
    String errorMsg = String.format("Exception occurred while executing parallel call");
    log.error(errorMsg, e);
    endResult = response.getItemGroupList();
}
finally {
    delayer.shutdown();
}

Response finalResponse = Response.builder()
    .itemGroupList(endResult)
    .build();
private <T> CompletableFuture<T> timeoutAfter(ScheduledExecutorService es,
    long timeout, TimeUnit unit, CompletableFuture<T> f, T value) {

    es.schedule(() -> f.complete(value), timeout, unit);
    return f;
}

在这里,supplyAsync产生CompletableFuture将提供getUpdatedItemGroup评估结果的 a。调用将timeoutAfter在超时后使用默认值安排完成,而不创建新的未来,然后,链接的依赖操作thenAccept会将结果值添加到result列表中。

注意 asynchronizedList允许从多个线程添加元素,但是从多个线程添加会导致不可预知的顺序,与源列表的顺序无关。


推荐阅读