Thomas Lang
Thomas Lang

Reputation: 1475

CompletableFuture join vs CompletableFuture thenApply

I have this two snippets in a Spring WebMVC controller:

First: thenApplyAsync

@RequestMapping(value = {"/index-standard"}, method = RequestMethod.GET)
    public CompletableFuture<String> indexStandard(Model model) {
        return projectService
                .findMine(getCurrentApplicationUser())
                .thenApplyAsync((result) -> {
                    model.addAttribute("projects", result);
                    return "/projectmanagement/my/index";
                });
    }

Second: join()

@RequestMapping(value = {"/index-nonstandard"}, method = RequestMethod.GET)
    public String indexNonStandard(Model model) {
        CompletableFuture<Iterable<ProjectDto>> mine = projectService.findMine(getCurrentApplicationUser());
        CompletableFuture.allOf(mine).join();
        model.addAttribute("projects", mine.join());
        return "/projectmanagement/my/index";
    }

For my understanding:

First option:

Second option:

What is the difference in these options?

So is there a preferable solution (first or second)?

Both options work.

Upvotes: 0

Views: 886

Answers (1)

Davide D&#39;Alto
Davide D&#39;Alto

Reputation: 8246

.join() will block the execution of the thread and wait until the result is ready. Usually, that's not the behaviour one wants when writing async applications.

Upvotes: 1

Related Questions