编程语言
首页 > 编程语言> > Java 8 CompletableFuture,Stream和Timeouts

Java 8 CompletableFuture,Stream和Timeouts

作者:互联网

我正在尝试使用CompletableFuture和Stream同时处理一些数据
到目前为止,我有:

public static void main(String[] args) throws InterruptedException, ExecutionException {
    System.out.println("start");

    List<String> collect = Stream.of("1", "2", "3", "4", "5",
            "6", "7")
            .map(x -> CompletableFuture.supplyAsync(getStringSupplier(x)))
            .collect(Collectors.toList())
            .stream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList());
    System.out.println("stop out!");
}


public static Supplier<String> getStringSupplier(String text) {
    return () -> {

        System.out.println("start " + text);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("stop " + text);
        return "asd" + text;
    };
}

输出很好:

开始
开始1
开始4
开始3
开始2
开始5
开始6
开始7
停止4
停止1
停止5
停止2
停止6
停止3
停止7
停下来!

但是现在我想为该工作添加超时.让我们说它应该在1 SECOND之后取消.并返回null或其他值来收集列表. (我希望有一些值表明原因).

我怎样才能实现这一目标?

提前感谢您的帮助.

解决方法:

我找到了这样做的方法:

 private static final ScheduledExecutorService scheduler =
        Executors.newScheduledThreadPool(
                1,
                new ThreadFactoryBuilder()
                        .setDaemon(true)
                        .setNameFormat("failAfter-%d")
                        .build());

public static void main(String[] args) throws InterruptedException, ExecutionException {
    System.out.println("start");
    final CompletableFuture<Object> oneSecondTimeout = failAfter(Duration.ofSeconds(1))
            .exceptionally(xxx -> "timeout exception");
    List<Object> collect = Stream.of("1", "2", "3", "4", "5", "6", "7")
            .map(x -> CompletableFuture.anyOf(createTaskSupplier(x)
                    , oneSecondTimeout))
            .collect(Collectors.toList())
            .stream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList());
    System.out.println("stop out!");
    System.out.println(collect);
}

public static CompletableFuture<String> createTaskSupplier(String x) {
    return CompletableFuture.supplyAsync(getStringSupplier(x))
            .exceptionally(xx -> "PROCESSING ERROR : " + xx.getMessage());
}


public static Supplier<String> getStringSupplier(String text) {
    return () -> {

        System.out.println("start " + text);
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (text.equals("1")) {
            throw new RuntimeException("LOGIC ERROR");
        }
        try {
            if (text.equals("7"))
                TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("stop " + text);
        return "result " + text;
    };
}

public static <T> CompletableFuture<T> failAfter(Duration duration) {
    final CompletableFuture<T> promise = new CompletableFuture<>();
    scheduler.schedule(() -> {
        final TimeoutException ex = new TimeoutException("Timeout after " + duration);
        return promise.completeExceptionally(ex);
    }, duration.toMillis(), MILLISECONDS);
    return promise;
}

它返回:

 start
 start 1
 start 3
 start 4
 start 2
 start 5
 start 6
 start 7
 stop 6
 stop 4
 stop 3
 stop 5
 stop 2
 stop out!
 [PROCESSING ERROR : java.lang.RuntimeException: LOGIC ERROR, result 2, result 3, result 4, result 5, result 6, timeout exception]`

您如何看待,您能发现该解决方案的任何缺陷吗?

标签:completable-future,java,java-8,java-stream,concurrency
来源: https://codeday.me/bug/20191007/1866112.html