gpt4 book ai didi

multithreading - 具有CompletableFutures的异步非阻塞任务

转载 作者:行者123 更新时间:2023-12-04 14:22:39 25 4
gpt4 key购买 nike

我需要在Java 8中创建一个异步的,非阻塞的任务,我想使用CompletableFutures,但是我不确定它是否满足我的需求。

为了简化这种情况,假设我们有一个API,可以为用户检索一些数据,但同时希望启动一个单独的任务来执行一些操作。我不需要也不想等待此单独的任务完成,我想立即将响应发送给用户。模拟代码中的一个示例:

public Response doSomething(params) {
Object data = retrieveSomeData(params);

// I don't want to wait for this to finish, I don't care if it succeeds or not
doSomethingNoWait(data);

return new Response(data);
}

我当时在看CompletableFutures,像这样:
CompletableFuture.supplyAsync(this::doSomethingNoWait)  
.thenApply(this::logSomeMessage);

我想知道那是正确的方法吗?在doSomethingNoWait完成必须做的事情之前,响应会返回给用户吗?

谢谢!

最佳答案

好问题。是的,CompleteableFuture非常适合您的需求!让我们进一步研究该类的功能。CompleteableFutureFuture类的包装,并允许并行执行。让我们来看一个来自this article的示例。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of the asynchronous computation";
});
在上面的示例中,程序将异步启动 CompletableFuture,并且新线程将在后台休眠。如果我们添加 .thenApply(),如下所示:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of the asynchronous computation";
}).thenApply(result -> {
System.out.println(result);
return "Result of the then apply";
});
该应用程序将像我们之前讨论的那样执行,但是一旦完成(非异常(exception)),当前运行 supplyAsync的线程将执行print语句。
请注意,如果在完成执行后将同步转换添加到将来,则调用线程将执行转换。正如我们在下面看到的:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of the asynchronous computation";
});
// Long calculations that allows the future above to finish
future.thenApply(result -> {
System.out.println(result);
return "Result of the then apply";
});
thenApply将在运行 future.thenApply(...)的线程上运行,而不是在后台生成的用于运行 supplyAsync的线程。

关于multithreading - 具有CompletableFutures的异步非阻塞任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51895840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com