n
Size: a a a
IZ
CompletableFuture<Integer> mustReturn42() {
CompletableFuture<Integer> fastRequest =
CompletableFuture.supplyAsync(() -> new Random().nextBoolean() ? 42 : 1);
CompletableFuture<Integer> slowRequest =
CompletableFuture.supplyAsync(
() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 41;
});
return fastRequest.thenApply(
result -> {
if (result == 42) {
return 42;
} else {
try {
return slowRequest.get() + result;
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
});
}E
IZ
E
IZ
E
IZ
IZ
CompletableFuture<Integer> fastResult = new CompletableFuture<>();
CompletableFuture<Void> fastRequest =
CompletableFuture.runAsync(
() -> {
if (new Random().nextBoolean()) {
fastResult.complete(42);
} else {
fastResult.complete(1);
}
});
CompletableFuture<Integer> slowRequest =
CompletableFuture.supplyAsync(
() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 41;
});
return fastRequest.thenCompose(
ignore -> {
try {
if (fastResult.get() == 42) {
return CompletableFuture.completedFuture(42);
} else {
return slowRequest.thenCombine(fastResult, (l, r) -> l + r);
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
IZ
E
IZ
IZ
E
IZ
IZ
IZ
CompletableFuture<Integer> mustReturn42() {
CompletableFuture<Integer> fastRequest = CompletableFuture.supplyAsync(
() -> {
if (new Random().nextBoolean()) {
return 42;
} else {
return 1;
}
});
CompletableFuture<Integer> slowRequest =
CompletableFuture.supplyAsync(
() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 41;
});
return fastRequest.thenCompose(
fastResult -> {
if (fastResult == 42) {
return CompletableFuture.completedFuture(42);
} else {
// this is a data race, right?
return slowRequest.thenApply(slowResult -> slowResult + fastResult);
}
});
}
есть ли тут гонка по данным?IZ
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
int my = 123;
future.thenApply(it -> it + my);
IZ