Execute multiple queries in parallel via Streams

后端 未结 4 1530
日久生厌
日久生厌 2020-12-14 05:00

I am having the following method:

public String getResult() {

        List serversList = getServerListFromDB();

        List ap         


        
4条回答
  •  眼角桃花
    2020-12-14 05:36

    You may utilize CompletableFuture this way:

    public String getResult() {
    
        // Create Stream of tasks:
        Stream>> tasks = Stream.of(
                () -> getServerListFromDB(),
                () -> getAppListFromDB(),
                () -> getUserFromDB());
    
        List> lists = tasks
             // Supply all the tasks for execution and collect CompletableFutures
             .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
             // Join all the CompletableFutures to gather the results
             .stream()
             .map(CompletableFuture::join).collect(Collectors.toList());
    
        // Use the results. They are guaranteed to be ordered in the same way as the tasks
        return getResult(lists.get(0), lists.get(1), lists.get(2));
    }
    

提交回复
热议问题