标签: completable-future

将未来可完成的异常映射到不同的异常类型?

我正在使用 java 8 的可完成的 future,我希望能够接受 future 抛出的异常并将其转换为不同的异常。

一旦发生异常,我尝试过的所有复合材料似乎都会短路。

例如,使用 scala future,我可以做这样的事情:

scala.concurrent.Future<Object> translatedException = ask.recover(new Recover<Object>() {
            @Override public Object recover(final Throwable failure) throws Throwable {
                if (failure instanceof AskTimeoutException) {
                    throw new ApiException(failure);
                }

                throw failure;
            }
        }, actorSystem.dispatcher());
Run Code Online (Sandbox Code Playgroud)

我希望能够在未来的 java 复合块中模仿这一点。这可能吗?

java exception completable-future

5
推荐指数
1
解决办法
3532
查看次数

为什么 CompletableFuture 的 thenAccept() 不在主线程上运行

我在 CompletableFuture 的 SupplyAsync() 中处理长时间运行的操作,并将结果放入 thenAccept() 中。有时 thenAccept() 在主线程上执行,但有时它在工作线程上运行。但我只想在主线程上运行 thenAccept() 操作。这是示例代码。

private void test() {

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
        System.out.println("supplyAsync | I am running on : " + Thread.currentThread().getName());
        return "Hello world";
    }, executorService);

    CompletableFuture<Void> cf3 = cf1.thenAccept(s -> {
        System.out.print("thenAccept | I am running on : " + Thread.currentThread().getName());
        System.out.println(" | answer : " + s);
    });

    cf3.thenRun(() -> {
        System.out.println("thenRun | I am running on : " + Thread.currentThread().getName());
        System.out.println();
    });

} …
Run Code Online (Sandbox Code Playgroud)

java completable-future

5
推荐指数
1
解决办法
5182
查看次数

嵌套期货未执行

我遇到了一个奇怪的情况。我正在摆弄CompletableFuture,当运行以下代码时,我得到了意想不到的结果:

public static void main(String[] args) {     
    CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<Object>>>>>> completableFutureCompletableFuture = CompletableFuture.supplyAsync(() -> {
        System.out.println("first");
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("second");
            return CompletableFuture.supplyAsync(() -> {
                System.out.println("third");
                return CompletableFuture.supplyAsync(() -> {
                    System.out.println("fourth");
                    return CompletableFuture.supplyAsync(() -> {
                        System.out.println("fifth");
                        return CompletableFuture.completedFuture(null);
                    });
                });
            });
        });
    });

   completableFutureCompletableFuture.get();
}
Run Code Online (Sandbox Code Playgroud)

没有抛出异常(即使使用时exceptionally),我看到的是控制台输出是

first
second
third // appears sometimes
Run Code Online (Sandbox Code Playgroud)

现在,显然这段代码没有真正的生产价值,但这代表了一种情况,即您的代码具有未知数量的嵌套,其中每个或其中一些嵌套创建的嵌套CompleteableFutures将不会被执行。

任何解释(以及如何修复的示例)将不胜感激

java multithreading completable-future

5
推荐指数
2
解决办法
2416
查看次数

从垃圾收集中不直观地驱逐对象

我正在调试内存泄漏,并且不得不深入了解 CompletableFuture 的内部结构。有这段代码(CompletableFuture.uniComposeStage):

CompletableFuture<V> g = f.apply(t).toCompletableFuture();
...
CompletableFuture<V> d = new CompletableFuture<V>();
UniRelay<V> copy = new UniRelay<V>(d, g);
g.push(copy);
copy.tryFire(SYNC);
return d;
Run Code Online (Sandbox Code Playgroud)

代码本身对我来说非常清楚:应用一个返回 CompletionStage ( g) 的函数,创建一个中继,最终将值传输到另一个 CompletableFuture ( d) ,然后返回另一个 future ( d) 。我看到以下参考情况:

  • copy引用dand g(构造函数中没有魔法,只有字段赋值)
  • g参考copy
  • d没有引用任何内容

仅d返回,因此,事实上,对我来说,g和copy似乎都是内部方法变量,(乍一看)永远不应该离开该方法并最终被GC。幼稚的测试和它是由经过验证的开发人员很久以前编写的事实都表明我错了并且遗漏了一些东西。是什么原因导致这些对象被垃圾收集忽略?

java garbage-collection completable-future

5
推荐指数
1
解决办法
510
查看次数

Java 中的异步 File.copy

Java中有没有一种方法可以以异步方式将一个文件复制到另一个文件中?我试图找到类似于C# 中的Stream.CopyToAsync的东西。

我想要实现的是从互联网下载一系列约 40 个文件,这是我为每个文件想到的最好的结果:

CompletableFuture.allOf(myFiles.stream()
        .map(file -> CompletableFuture.supplyAsync(() -> syncDownloadFile(file)))
        .toArray(CompletableFuture[]::class))
    .then(ignored -> doSomethingAfterAllDownloadsAreComplete());
Run Code Online (Sandbox Code Playgroud)

哪里syncDownloadFile:

private void syncDownloadFile(MyFile file) {
    try (InputStream is = file.mySourceUrl.openStream()) {
        long actualSize = Files.copy(is, file.myDestinationNIOPath);
        // size validation here
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这意味着我在任务执行器内部有一些阻塞调用,我想避免这种情况,所以我不会一次阻塞太多执行器。

我不确定 C# 方法内部是否执行相同的操作(我的意思是,必须有东西下载该文件,对吗?)。

有更好的方法来实现这一点吗?

java nio completable-future

5
推荐指数
1
解决办法
1698
查看次数

如果没有多线程,使用Future有什么意义呢?

我继承了一些代码,原来的开发人员已经没有人留下了。该代码大量使用了CompletableFuture,这是我第一次使用它,所以我仍在尝试理解它。据我了解, a(Completable)Future通常与某种多线程机制一起使用,该机制允许我们在执行耗时的任务时执行其他操作,然后只需通过 Future 获取其结果。正如javadoc中所示:

interface ArchiveSearcher { String search(String target); }
class App {
    ExecutorService executor = ...
    ArchiveSearcher searcher = ...
    void showSearch(final String target) throws InterruptedException {
        Future<String> future = executor.submit(new Callable<String>() {
        public String call() {
            return searcher.search(target);
        }});
        displayOtherThings(); // do other things while searching
        try {
            displayText(future.get()); // use future
        } catch (ExecutionException ex) { cleanup(); return; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,在我继承的这个应用程序中,以下不使用任何多线程的模式多次出现:

public Object serve(Object input) throws ExecutionException, InterruptedException { …
Run Code Online (Sandbox Code Playgroud)

java multithreading asynchronous future completable-future

5
推荐指数
1
解决办法
1839
查看次数

从 CompletableFuture.allof() 获取单独的结果

我有一个类,它使用 CompletableFutures 向两个依赖服务发出并发请求。

我的代码如下所示:

@Builder
@Slf4j
public class TestClass {

    @NonNull private final ExecutorService threadPool = Executors.newFixedThreadPool(2);
    @NonNull private final dependency1Client;
    @NonNull private final dependency2Client;

    public void myMethod() {

        RequestObject1 firstDependencyRequest = RequestObject1.builder()
                .attribute1("someValue")
                .attribute2("secondValue");

        CompletableFuture<ResultStructure1> future1 = CompletableFuture.supplyAsync(() -> dependency1Client.call(firstDependencyRequest), threadPool);
        RequestObject2 secondDependencyRequest = RequestObject2.builder()
                .attribute1("someValue")
                .attribute2("secondValue");

        CompletableFuture<ResultStructure2> future2 = CompletableFuture.supplyAsync(() -> dependency2Client.call(secondDependencyRequest), threadPool);

        try {
            CompletableFuture finalFuture = CompletableFuture.allOf(future1, future2);

        } catch (ExecutionException|InterruptedException e) {
            log.error("Exception calling dependency", e);
            throw new RuntimeException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要对依赖服务的两次调用的结果。如何在不执行阻塞调用的情况下获取它们?我最初以为我会执行 future1 .get(),但这是一个阻塞调用,我必须等到获得第一个 …

java concurrency completable-future

5
推荐指数
1
解决办法
4405
查看次数

如何将已检查的异常从 CompletableFuture 传递给 ControllerAdvice

如何让 controllerAdvice 类捕获从 completablefutrue 抛出的异常。在下面的代码中,我有一个checkId抛出已检查异常的方法。我使用 completablefuture 调用此方法并将已检查的异常包装在 CompletionException 中。虽然我在控制器通知类中有一个处理程序方法,但它没有处理错误。

package com.example.demo.controller;
@RestController
public class HomeController {

    @GetMapping(path = "/check")
    public CompletableFuture<String> check(@RequestParam("id") int id) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return checkId(id);
            }
            catch (Exception e) {
                throw new CompletionException(e);
            }
        });
    }

    public String checkId(int id) throws Exception  {
        if (id < 0) {
            throw new MyException("Id must be greater than 0");
        }
        return "id is good";
    }

}
Run Code Online (Sandbox Code Playgroud)

——

package com.example.demo;
public class MyException extends …
Run Code Online (Sandbox Code Playgroud)

java spring java-8 completable-future controller-advice

5
推荐指数
1
解决办法
876
查看次数

CompletableFuture 异常处理 runAsync &amp; thenRun

假设我有这个示例代码并且在runAsync. 我的问题是这个异常是否会阻止在thenRun与thenRun此代码的调用方方法相同的线程中运行时被执行。

private void caller() {
    CompletableFuture.runAsync(() -> {
          try {
              // some code
          } catch (Exception e) {
              throw new CustomException(errorMessage, e);
          }
         }, anInstanceOfTaskExecutor).thenRun(
         // thenRun code
     ));
}
Run Code Online (Sandbox Code Playgroud)

我已经浏览了这个线程,它解释了如何处理从异步块抛出的异常(即通过阻塞和使用join)。我想知道thenRun如果CompletableFuture completesExceptionally.

更新:

我运行了一些代码来测试这个:

CompletableFuture.runAsync(() -> {
      List<Integer> integerList = new ArrayList<>();
      integerList.get(1);    // throws exception
    }).thenRun(() -> {
      System.out.println("No exception occurred");
    });
Run Code Online (Sandbox Code Playgroud)

它不打印任何内容,这意味着异常不会从异步块“传播到/到达”调用方方法的线程。我现在了解这里的预期行为,但我有以下问题:

  1. 为什么即使 CompletableFuture 完成异常,它也会默默失败?
  2. 它在后台如何工作?
  3. 是不是因为这两个线程(调用者的线程和异步线程)都有自己的堆栈空间?

java asynchronous exception java-8 completable-future

5
推荐指数
2
解决办法
5453
查看次数

等待 List&lt;CompletableFuture&lt;Void&gt;&gt; 指示所有操作已完成的正确方法

我正在使用 runAsync() 运行数百个函数。所有的函数都会修改一些静态可用的列表,因此不需要返回任何内容。在继续我的处理之前,我想确保它们都完成了。这是适当的等待方式吗?有没有更简单的方法来完成我想要做的事情?

List<CompletableFuture<Void>> futures = new ArrayList<>();
active_sites.forEach(site -> site.getEntryPoints().stream().map(EntryPoint::scanEntryPoint).forEach(futures::add));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
Run Code Online (Sandbox Code Playgroud)

java multithreading completable-future java-15

5
推荐指数
1
解决办法
142
查看次数