err*_*ist 8 multithreading asynchronous future java-8 completable-future
我有一个创建成本很高的对象映射,因此我想创建对象并与应用程序中的其他进程并行填充映射。只有当主线程实际需要访问地图时,应用程序才应等待填充地图的异步任务完成。我怎样才能最优雅地做到这一点?
目前,我能够使用CompletableFuture.runAsync(Runnable, Executor)类似于下面的示例代码中的方式异步创建地图本身中的每个单独对象,但我不确定如何构建Future/ CompletableFuture-type 机制以Map在准备好时返回自身:
public static class AsynchronousMapPopulator {
private final Executor backgroundJobExecutor;
public AsynchronousMapPopulator(final Executor backgroundJobExecutor) {
this.backgroundJobExecutor = backgroundJobExecutor;
}
public ConcurrentMap<String, Integer> apply(final Map<String,Integer> input) {
final ConcurrentMap<String, Integer> result = new ConcurrentHashMap<>(input.size());
final Stream.Builder<CompletableFuture<Void>> incrementingJobs = Stream.builder();
for (final Entry<String, Integer> entry : input.entrySet()) {
final String className = entry.getKey();
final Integer oldValue = entry.getValue();
final CompletableFuture<Void> 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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,对于上面的代码,当代码调用 时AsynchronousTest.create(Map<String,Integer),它已经阻塞,直到该方法返回完全填充的ConcurrentMap<String,Integer>; 我怎样才能把它变成类似 a 的东西,Future<Map<String,Integer>>以便我以后可以使用它?:
Executor someExecutor = ForkJoinPool.commonPool();
Future<Map<String,Integer>> futureClassModels = new AsynchronousMapPopulator(someExecutor).apply(wordClassObservations);
...
// Do lots of other stuff
...
Map<String,Integer> completedModels = futureClassModels.get();
Run Code Online (Sandbox Code Playgroud)
正如 @Holger 在他的评论中指出的那样,您必须避免调用.join()并依赖thenApply(),例如这样:
public static class AsynchronousMapPopulator {
private final Executor backgroundJobExecutor;
public AsynchronousMapPopulator(final Executor backgroundJobExecutor) {
this.backgroundJobExecutor = backgroundJobExecutor;
}
public Future<Map<String, Integer>> apply(final Map<String,Integer> input) {
final ConcurrentMap<String, Integer> result = new ConcurrentHashMap<>(input.size());
final Stream.Builder<CompletableFuture<Void>> incrementingJobs = Stream.builder();
for (final Entry<String, Integer> entry : input.entrySet()) {
final String className = entry.getKey();
final Integer oldValue = entry.getValue();
final CompletableFuture<Void> incrementingJob = CompletableFuture.runAsync(() -> {
result.put(className, oldValue + 1);
}, backgroundJobExecutor);
incrementingJobs.add(incrementingJob);
}
// using thenApply instead of join here:
return CompletableFuture.allOf(
incrementingJobs.build().toArray(
CompletableFuture[]::new
)
).thenApply(x -> result);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4406 次 |
| 最近记录: |