这是我的简单代码:
public class Main4 {
public static void main(String[] args) {
System.out.println("Hello from thread: "+Thread.currentThread().getName());
new Game().run();
System.out.println("I am dying ... ");
}
static class Game {
public void run() {
value();
}
private int value() {
int number = 0;
CompletionStage<Void> c = calculate().thenApply(i -> i + 3).thenAccept(i -> System.out.println("I am done, and my value is " + i));
return number;
}
private CompletionStage<Integer> calculate() {
CompletionStage<Integer> completionStage = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
System.out.println("I am in the thread: …Run Code Online (Sandbox Code Playgroud) java multithreading threadpool completable-future completion-stage
该CompletableFutureAPI 允许我们用来thenCompose链接另一个 future:
CompletableFuture<String> future1 = submit("foo");
CompletableFuture<String> future2 = future.thenCompose((result) -> submit(result));
Run Code Online (Sandbox Code Playgroud)
但这仅适用于成功的响应。有没有办法做同样的事情,但还包括异常处理?
例如:
CompletableFuture<String> future1 = submit("foo");
CompletableFuture<String> future2 = future.handleCompose((result, error) -> {
if (error != null)
return submit("failure"); // Handle error by doing a different action with the same result (like a fallback)
else
return submit(result);
});
Run Code Online (Sandbox Code Playgroud)
我知道你可以这样做whenComplete:
CompletableFuture<String> future2 = new CompletableFuture<>();
CompletableFuture<String> future1 = submit("foo");
future.whenComplete((result, error) -> {
CompletableFuture<String> tmp;
if (error != null)
tmp = submit("failure"); …Run Code Online (Sandbox Code Playgroud) 只是浏览CompletableFuture文档并偶然发现了completeExceptionally和obtrudeException方法,并且很难理解差异和用例。社区可以通过示例帮助理解差异和用例吗?
java multithreading asynchronous completable-future completion-stage
当一个人将 CompletableFuture 与 Executor 一起使用时。这些任务是否在不同的内核上运行?或者它可能是相同的核心,但只是来自 Theadpool 的线程?在文档中我无法阅读任何有关它的内容。该任务将在创建 10 个任务的 for 循环中运行。这些会在不同的内核上运行吗?我怎样才能检查这个?谢谢
Executor testExecutor = Executors.newFixedThreadPool(5);
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung",testExecutor);
Run Code Online (Sandbox Code Playgroud) 该类CompletableFuture允许添加在调用后未来完成时调用的操作complete(...).
我可以使用whenComplete(...)来添加多个BiConsumer动作完成以后,并且当所有的人都在执行时执行complete(...)方法被调用?
我有检查CompletableFuture执行时间的方法.如果此类CompletableFuture执行的时间超过2秒,我想要终止此任务.但是,如果我没有执行CompletableFuture方法的控制线程,我该怎么办呢?
final CompletableFuture<List<List<Student>>> responseFuture = new CompletableFuture<>();
responseFuture.supplyAsync(this::createAllRandomGroups)
.thenAccept(this::printGroups)
.exceptionally(throwable -> {
throwable.printStackTrace();
return null;
});
Run Code Online (Sandbox Code Playgroud)
createAllRandomGroups()
private List<List<Student>> createAllRandomGroups() {
System.out.println("XD");
List<Student> allStudents = ClassGroupUtils.getActiveUsers();
Controller controller = Controller.getInstance();
List<List<Student>> groups = new ArrayList<>();
int groupSize = Integer.valueOf(controller.getGroupSizeComboBox().getSelectionModel().getSelectedItem());
int numberOfGroupsToGenerate = allStudents.size() / groupSize;
int studentWithoutGroup = allStudents.size() % groupSize;
if (studentWithoutGroup != 0) groups.add(this.getListOfStudentsWithoutGroup(allStudents, groupSize));
for(int i = 0; i < numberOfGroupsToGenerate; i++) {
boolean isGroupCreated = false;
while (!isGroupCreated){
Collections.shuffle(allStudents);
List<Student> newGroup = this.createNewRandomGroupOfStudents(allStudents, groupSize);
groups.add(newGroup);
if …Run Code Online (Sandbox Code Playgroud) 我有一个用例,我想根据我在元素上执行的网络调用过滤出列表中的一些元素.为了实现这一点,我使用流,过滤器和Completable Future.目标是执行异步执行,以便操作变得高效.下面提到伪代码.
public List<Integer> afterFilteringList(List<Integer> initialList){
List<Integer> afterFilteringList =initialList.stream().filter(element -> {
boolean valid = true;
try{
valid = makeNetworkCallAndCheck().get();
} catch (Exception e) {
}
return valid;
}).collect(Collectors.toList());
return afterFilteringList;
}
public CompletableFuture<Boolean> makeNetworkCallAndCheck(Integer value){
return CompletableFuture.completedFuture(resultOfNetWorkCall(value);
}
Run Code Online (Sandbox Code Playgroud)
我在这里遇到的问题是,我是否以异步方式进行此操作?(因为我在过滤器中使用'get'函数会阻止执行并使其仅为顺序)或者是否有更好的方法使用Java 8中的Completable Future和Filters以异步方式执行此操作.
我正在以这种方式进行异步 http 调用
public CompletableFuture<String> doPost(String path, String json) {
CompletableFuture<String> result = new CompletableFuture<>();
Request request = new Request.Builder().url(this.address + path).post(RequestBody.create(json, JSON)).build();
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
result.completeExceptionally(new TerminationException());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
result.complete(response.body().string());
}
});
}
Run Code Online (Sandbox Code Playgroud)
但响应可能包含我需要重试的代码之一,代码应该是
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (!retries.contains(responce.code()) {
result.complete(response.body().string());
} else {
// Do retry here
} …Run Code Online (Sandbox Code Playgroud) 我想打电话给cancel上CompletableFuture。
从文档看来:
如果尚未完成,则使用 CancellationException 完成此 CompletableFuture。尚未完成的从属 CompletableFutures 也将异常完成,此 CancellationException 会导致 CompletionException。
它应该异常地完成它们,这正是我所期望的,但相反,它会立即抛出 CancellationException。
这是一个示例代码
CompletableFuture<?> f = CompletableFuture.supplyAsync(() -> false);
f.cancel(true); // Line 7.
f.join();
Run Code Online (Sandbox Code Playgroud)
使用重现:https : //www.mycompiler.io/view/2v1ME4u
Exception in thread "main" java.util.concurrent.CancellationException
at java.base/java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2396)
at Main.main(Main.java:7)
Run Code Online (Sandbox Code Playgroud)
7号线是f.cancel(true);线。
java concurrency java.util.concurrent java-8 completable-future