[如何使用CompletableFuture在Java 8中将此代码转换为异步代码?我正在使用Spring Boot

问题描述 投票:1回答:1

这里是需要异步的代码片段:

List<Course> courses = Lists.newArrayList();
Map<String, Map<String, Student>> result = Maps.newHashMap();

for (Map<String, Object> map : jsonObject) {
   courses.add(getCourse(map, fee));  
   result.put(map.get(GROUP), getInfoMap(map));  
}

PS:map循环中的for-each在两个方法调用中均未发生突变,它们仅使用信息。

如何使以上代码异步运行?有两种方法分别称为getCourse(map, fee)getInfoMap(map),要花很多时间才能依次运行它们。]

这里是需要异步的代码段:List courses = Lists.newArrayList(); Map > result = Maps.newHashMap();对于(Map

java multithreading spring-boot asynchronous completable-future
1个回答
0
投票
    // start parallel operations
    List<Future<Course>> coursesFut = Lists.newArrayList();
    Map<String, Future<Map<String, Student>>> resultsFut = Maps.newHashMap();
    for (Map<String, Object> map : jsonObjec t){
        coursesFut.add(CompletableFuture.supplyAsync(() -> getCourse(map, fee)));
        resultsFut.put(map.get(GROUP), CompletableFuture.supplyAsync(() -> getInfoMap(map)));
    }

    // collect results
    List<Course> courses = Lists.newArrayList();
    Map<String, Map<String, Student>> result = Maps.newHashMap();
    for (Future<Course> cf : coursesFut) {
        courses.add(cf.get());
    }
    for (Map.Entry<String, Future<Map<String, Student>> entry : resultsFut.entrySet()) {
        result.put(entry.getKey(), entry.getValue().get());
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.