我有一个对象的地图,这些对象的创建成本很高,所以我想创建对象并与我的应用程序中的其他进程并行填充地图.只有当主线程实际需要访问映射时,应用程序才会等待填充映射的异步任务完成.我怎样才能最优雅地完成这项工作?
目前的做法
目前,我能够在下面的示例代码中使用CompletableFuture.runAsync(Runnable, Executor)类似于异步创建地图本身中的每个单独对象,但我不确定如何构建Future / CompletableFuture类型机制,以便在准备好时返回Map本身:
public static class AsynchronousMapPopulator {
private final Executor backgroundJobExecutor;
public AsynchronousMapPopulator(final Executor backgroundJobExecutor) {
this.backgroundJobExecutor = backgroundJobExecutor;
}
public ConcurrentMap apply(final Map input) {
final ConcurrentMap result = new ConcurrentHashMap<>(input.size());
final Stream.Builder> incrementingJobs = Stream.builder();
for (final Entry entry : input.entrySet()) {
final String className = entry.getKey();
final Integer oldValue = entry.getValue();
final CompletableFuture incrementingJob = CompletableFuture.runAsync(() -> {
result.put(className, oldValue + 1);
}, backgroundJobExecutor);
incrementingJobs.add(incrementingJob);
}
// TODO: This blocks until the training is done; Instead, return a
// future to the caller somehow
CompletableFuture.allOf(incrementingJobs.build().toArray(CompletableFuture[]::new)).join();
return result;
}
}
但是,使用上面的代码,当代码调用AsynchronousTest.create(Map< String,Integer)时,它已经阻塞,直到该方法返回完全填充的ConcurrentMap< String,Integer> ;;如何将其转换为Future< Map< String,Integer>>以便我以后可以使用它?:
Executor someExecutor = ForkJoinPool.commonPool();
Future> futureClassModels = new AsynchronousMapPopulator(someExecutor).apply(wordClassObservations);
...
// Do lots of other stuff
...
Map completedModels = futureClassModels.get();