Async-Await in Vertx with Project Loom
August Nagro
augustnagro at gmail.com
Wed Oct 27 02:48:33 UTC 2021
To make the sequential Async-Await code parallel, we could define a method
'awaitAll' (which is probably be a good addition to the library):
public static <A> List<A> awaitAll(List<CompletionStage<A>> stages) {
return stages.stream().map(stage -> await(stage)).toList();
}
And change the sequential part from
List<String> userNames = userIds.stream()
.map(id -> await(userNamesFromSomeApi(id)))
.toList();
To:
List<String> userNames = awaitAll(
userIds.stream()
.map(id -> userNamesFromSomeApi(id))
.toList()
);
To make the CompletableFuture example sequential, we could make a chain of
thenCompose operations. So From:
List<CompletableFuture<String>> userNameFutures = userIds.stream()
.map(id -> userNamesFromSomeApi(id))
.map(CompletionStage::toCompletableFuture)
.toList();
CompletableFuture.allOf(userNameFutures.toArray(new CompletableFuture[0]))
.thenCompose(voidd -> {...});
To:
CompletionStage<List<String>> userNames =
CompletableFuture.supplyAsync(() -> new ArrayList<>());
for (Long userId : userIds) {
userNames = userNames.thenCompose(list -> {
return userNamesFromSomeApi(userId)
.thenApply(userName -> {
list.add(userName);
return list;
});
});
}
userNames.thenCompose(...)
Overall, I think async-await is nicer than flatMap/thenCompose chains. And
'just blocking' on a virtual thread is even nicer.
On Fri, Oct 22, 2021 at 7:26 AM Alex Otenko <oleksandr.otenko at gmail.com>
wrote:
> That example doesn't appear to be comparable.
>
> CompletableFuture example is parallel, async/await is sequential.
>
> It would be great to see the amount of boilerplate needed to implement
> both in both cases.
>
> Alex
>
> On Mon, 18 Oct 2021, 04:15 August Nagro, <augustnagro at gmail.com> wrote:
>
>> Hello; I recently implemented async/await in Vertx using Project Loom.
>>
>> Feedback and code review are very welcome. The project is only about 100
>> lines of code. Hopefully something similar could be merged into
>> `vertx-core` when Loom is released.
>>
>> https://github.com/AugustNagro/vertx-loom
>>
>> Cheers,
>>
>> August
>>
>
More information about the loom-dev
mailing list