如何从Java 8中的CompletableFuture <List <CustomObject >>获取结果

时间:2019-12-04 19:20:45

标签: java java-8 concurrency

Java 8环境。

同时使用CompletableFuture.allOf()运行任务,并 然后从每个线程获取每个结果,然后将所有结果合并到一个CombinedResult中并返回。

在下面的代码中,获取结果(= List<Student>)不必是I.和II之间的代码。 他们说我需要使用join()但没有用

我也从

那里得到了allOf()

Java 8 CompletableFuture.allOf(...) with Collection or List
和其他链接,但对我没有任何帮助。 我想我错过了一些非常简单的部分。有人知道如何使其工作吗?

public class Test1 {
    public static void main(String[] args) {
        Test1 t = new Test1();
        Map<Major, List<Student>> allMajorStudentListMap = new HashMap<>();
        // fill out some data toallMajorStudentListMap
        t.getData(allMajorStudentListMap);
    }

    List<Student> getData(Map<Major, List<Student>> allMajorStudentListMap) {
        List<CompletableFuture<List<Student>>> completableFutures = new ArrayList<>();

        // suppose the size of completableFutures is 10
        for(Map.Entry<Major, List<Student>> entry: allMajorStudentListMap.entrySet()) {
            CompletableFuture<List<Student>> future = CompletableFuture.supplyAsync(() -> getDetailedStudents(entry));
            completableFutures.add(future);
        }

        // want to run 10 jobs concurrently --> get the 10 result and then combine these 10 results into one
        // finally want to sent the combined 10 results at one in this method

        // I. ======================= I got this code from somewhere     ==========================

        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
                .exceptionally(ex -> null)
                .join();

        Map<Boolean, List<CompletableFuture<List<Student>>>> result =
                completableFutures.stream()
                        .collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));

        result.forEach((k, clist) -> {
            System.out.printf("k = " + k);

            for(CompletableFuture<List<Student>> student: clist) {

            // 3) don't know how to get only List<Student> and then print here
            // tried this and that but didn't work
            // student.get() has compile error

            }

        });

        // II. =============================================================================================


        // want to return combined List<Student>
        return ???;
    }

    List<Student> getDetailedStudents(Map.Entry<Major, List<Student>> entry) 
    {
        List<Student> studentList = new ArrayList<>();

        Major major = entry.getKey();
        String majorCode = major.getMajorCode();
        String majorName = major.getMajorName();
        List<Student> studentListList = entry.getValue();           

        studentList.addAll(getDataFromRemote(majorCode, majorName, studentList)));
        return studentList;
    }

    List<Student> getDataFromRemote(String majorCode, String majorName, List<studentList> studentList) {
        // do something and then return list of Student

        return detailedStudentList;
    }
}

1 个答案:

答案 0 :(得分:1)

在这里,我创建了一个稍有改动的(直接使用List<Student>而不是Map<K,V>版本的工作示例。您可以将您的解决方案与此解决方案进行比较。

总共查询五次学生名单,并且每次并发执行一次,这在人为延迟3秒后返回了其中有一个学生对象的完整学生名单。因此从理论上讲,如果每个对象同时运行,则在延迟3秒后,应该显示所有5个学生对象。

如果您注意到主方法的开始和结束之间的时间间隔,则大约为3秒。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.*;
import java.util.stream.Collectors;

public class CompletableFutureTest {
    private static int counter = 0;
    public static void main(String[] args) {
        System.out.println("Program started at " + new Date());
       List<Student> allStudents = new ArrayList<>();
        new CompletableFutureTest().getData(allStudents);
        for(Student st : allStudents){
            System.out.println(st.getName());
        }
        System.out.println("Program ended at " + new Date());
    }

    private void getData(List<Student> resultToFillIn){
        List<CompletableFuture<List<Student>>> completableFutures = new ArrayList<>();
        //for simulation purpose just running regular for loop 5 times instead of yours          
        final Integer integer = new Integer(0);
        for(int i=0; i < 5; i++){
            completableFutures.add(CompletableFuture.supplyAsync(() -> getStudentsBatch()));
        }
        CompletableFuture<List<Student>>[] cfArray = new CompletableFuture[completableFutures.size()];
        cfArray = completableFutures.toArray(cfArray);
        CompletableFuture.allOf(cfArray)
                .exceptionally(ex ->
                {
                    ex.printStackTrace();
                    return null;
                }).join();
       List<CompletableFuture<List<Student>>> completedFutures = completableFutures.stream().filter(cf -> !cf.isCompletedExceptionally()).collect(Collectors.toList());
       for(CompletableFuture<List<Student>> cf : completedFutures){
           resultToFillIn.addAll(cf.join());
       }
    }

    private List<Student> getStudentsBatch() {
        //adding some delay
        try {
            Thread.sleep( 3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<Student> students = new ArrayList<>();
        Student student = new Student();
        student.setName("Student " + ++counter);
        students.add(student);
        return students;
    }

    public static class Student{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class Major{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

由于此操作如上所述,因此CompletableFuture.allOf(...)正常工作。

但是,请尽量避免使用j oin(),因为它会暂停当前正在执行的线程。如果您选择真正的异步编程,则可以使用join()thenAccept(x -> {})回调方法来代替thenApply(x -> {})

希望这对您有所帮助。