[英]How to convert this code to async in Java 8 using CompletableFuture ? I am using Spring Boot
Here is the Code Snippet that needs to be made async:这是需要异步的代码片段:
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: the map
in the for-each
loop is not mutated in both the method calls, only the information is used by them. PS:
for-each
循环中的map
在两个方法调用中都没有发生突变,它们仅使用信息。
How can I make the above code run async?如何使上述代码异步运行? There are two methods being called
getCourse(map, fee)
and getInfoMap(map)
and it takes quite a time to run them sequentially.有两种方法被称为
getCourse(map, fee)
和getInfoMap(map)
,顺序运行它们需要相当长的时间。
// 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.