适合多次调用CompletableFuture#join吗?

时间:2019-11-08 18:14:50

标签: java asynchronous

在提供必须首先加载到内存的资源的类中,这是我的模式:

public class FooService {
    private final CompletableFuture<Void> loaded;
    public FooService() {
        this.loaded = CompletableFuture.runAsync(() -> {
            // Do some task that shouldn't hold up constructing
        });
    }

    public Foo get(String bar) {
        this.loaded.join(); // Ensure we have loaded everything before continuing
        return something;
    }
}

以这种方式使用CompletableFuture是否合适(多次调用join()会在相对较短的时间后成为一个完整的未来)?还是应该使用标志并等待/通知?上面的方法比较干净,但是CompletableFuture文档没有指定是否可以多次调用join。

1 个答案:

答案 0 :(得分:0)

您的方法有效。但是,可以通过将join替换为get来优化代码的大小:

public class FooService {
    private final CompletableFuture<Void> loaded;
    public FooService() {
        this.loaded = CompletableFuture.supplyAsync(() -> {
           // Do some task that shouldn't hold up constructing
            return something;
        });
   }

    public Foo get(String bar) {
        return this.loaded.get(); // Ensure we have loaded everything before continuing
    }
}