实施 CompletableFuture 时出错 "CompletableFuture(Object) has private access in CompletableFuture"

Error saying "CompletableFuture(Object) has private access in CompletableFuture" when implementing CompletableFuture

我正在按如下方式实施 CompletableFuture,但收到一条错误消息

CompletableFuture(Object) has private access in CompletableFuture

public CompletableFuture<A> init(B b) {

    C c = new C();  
    CompletableFuture<A> future = new CompletableFuture<A>(c);

    return future;
}

public class C implements Callable<A> {

    public A call() throws Exception {
        A a = new A();
        return a;
    }
}

我希望解决这个错误?

CompletableFuture class 中没有接受参数的 public 构造函数。最好使用 CompletableFuture.supplyAsync() 静态方法,它采用 Supplier 而不是 Callable:

CompletableFuture<A> future = CompletableFuture.supplyAsync(A::new);

或使用 lambda:

CompletableFuture<A> future = CompletableFuture.supplyAsync(() -> new A());

注意如果A构造函数抛出checked exception,你应该按Supplier接口不支持异常处理:

CompletableFuture<A> future = CompletableFuture.supplyAsync(() -> {
    try { return new A(); }
    catch(Exception ex) { throw new RuntimeException(ex);}
});

最后请注意,supplyAsync 不仅会创建 CompletableFuture,还会安排它在公共线程池中执行。您可以将自定义 Executor 指定为 supplyAsync 方法的第二个参数。如果你想创建 CompletableFuture 而不立即发送它来执行,那么你可能不需要 CompletableFuture.