通过Streams并行执行多个查询

Zee*_*han 9 java parallel-processing java-8 java-stream

我有以下方法:

public String getResult() {

        List<String> serversList = getServerListFromDB();

        List<String> appList = getAppListFromDB();

        List<String> userList = getUserFromDB();

        return getResult(serversList, appList, userList);
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我按顺序调用三个方法,然后点击DB并获取结果,然后我对从DB命中获得的结果进行后处理.我知道如何通过使用同时调用这三种方法Threads.但我想用Java 8 Parallel Stream来实现这一目标.有人可以指导我如何通过Parallel Streams实现同样的目标吗?

编辑我只想通过Stream并行调用方法.

private void getInformation() {
    method1();
    method2();
    method3();
    method4();
    method5();
}
Run Code Online (Sandbox Code Playgroud)

Tag*_*eev 13

你可以这样使用CompletableFuture:

public String getResult() {

    // Create Stream of tasks:
    Stream<Supplier<List<String>>> tasks = Stream.of(
            () -> getServerListFromDB(),
            () -> getAppListFromDB(),
            () -> getUserFromDB());

    List<List<String>> 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));
}
Run Code Online (Sandbox Code Playgroud)