异步填充Java Map并将其作为未来返回

时间:2017-11-07 11:28:43

标签: multithreading asynchronous java-8 future completable-future

我有一张对象的地图,这些对象的制作成本很高,所以我想创建对象并与我的应用程序中的其他进程并行填充地图。只有当主线程实际需要访问映射时,应用程序才会等待填充映射的异步任务完成。我怎样才能最优雅地完成这项工作?

目前的方法

目前,我能够使用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<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;
    }
}

但是,使用上面的代码,当代码调用AsynchronousTest.create(Map<String,Integer)时,它已经阻塞,直到该方法返回完全填充的ConcurrentMap<String,Integer>;如何将其转换为类似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();

1 个答案:

答案 0 :(得分:1)

正如@Holger在评论中所述,您必须避免致电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); } } ,例如像这样:

override var prefersStatusBarHidden: Bool {
    return true
}