In my SpringBoot application I have a endpoint that needs to return data in an async way. The method is populating the data but when testing via postman it is returning 200 OK with blank data. I have tried the below 2 approaches but both are returning blank response. Requesting to please check and suggest.
Approach 1
@Async(value = "threadPoolTaskExecutor")
public List<Movie> getMoviesOfHeroASync() throws ExecutionException, InterruptedException {
List<Movie> allMoviesOfHeroesList = new ArrayList<>();
String heroes = "aaa;bbb;ccc";
List<CompletableFuture<Map<String, List<Movie>>>> completableFutureList = Arrays.stream(heroes.split(";")).map(this::getMoviesOfHero).toList();
CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[0])).join();
for(CompletableFuture<Map<String, List<Movie>>> completableFuture : completableFutureList){
if(!completableFuture.get().isEmpty()) {
completableFuture.get().values().stream().findAny().ifPresent(allMoviesOfHeroesList::addAll);
}
}
return allMoviesOfHeroesList;
}
Approach 2
@Async(value = "threadPoolTaskExecutor")
public List<Movie> getMoviesOfHeroASync() throws ExecutionException, InterruptedException {
List<Movie> allMoviesOfHeroesList = new ArrayList<>();
String heroes = "aaa;bbb;ccc";
List<CompletableFuture<Map<String, List<Movie>>>> completableFutureList = Arrays.stream(heroes.split(";")).map(this::getMoviesOfHero).toList();
CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[0]))
.thenApplyAsync(value -> {
for(CompletableFuture<Map<String, List<Movie>>> completableFuture : completableFutureList){
try {
if(!completableFuture.get().isEmpty()) {
completableFuture.get().values().stream().findAny().ifPresent(allMoviesOfHeroesList::addAll);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
return null;
});
return allMoviesOfHeroesList;
}