简体   繁体   English

CompletableFuture 中的异常传播 (java)

[英]Exception propagation in CompletableFuture (java)

How can I propagate exception encountered in the following code inside CompletableFuture.runAsync to my main thread?如何将CompletableFuture.runAsync中的以下代码中遇到的异常传播到我的主线程? I want to catch the IllegalStateException in my main thread.我想在我的主线程中捕获IllegalStateException

CompletableFuture.runAsync(() -> {
        // some business logic which needs to run indefinitely
}).exceptionally(ex -> {
    // ex.printStackTrace();
    throw new IllegalStateException("Failed to process", ex);
});

One option would be to create a Collection of Throwable objects and when the CompletableFuture completes you can add the exception to the Collection (if it's not null).一种选择是创建Throwable对象的Collection ,当CompletableFuture完成时,您可以将异常添加到集合中(如果它不为空)。 Then on your main thread you could poll that Collection.然后在您的主线程上,您可以轮询该集合。

        Set<Throwable> exception = new CopyOnWriteArraySet<>();

        CompletableFuture.runAsync(() -> {

        }).whenComplete((method, e) -> exception.add(e));

Another option is to use whenComplete with ExecutorService .另一种选择是将whenCompleteExecutorService一起使用。 This may not work if you're not using an ExecutorService.如果您不使用 ExecutorService,这可能不起作用。 The idea is that whenComplete will return on the mainThread ExecutorService.这个想法是whenComplete将在mainThread ExecutorService 上返回。

        ExecutorService mainThread = Executors.newSingleThreadExecutor();
        
        CompletableFuture.runAsync(() -> {

        }).whenCompleteAsync((method, throwable) -> {
            // throw or handle in some way on main thread
        }, mainThread);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM