Java 在CompletableFuture回调中为类成员属性设置值是否线程安全?

Java 在CompletableFuture回调中为类成员属性设置值是否线程安全?,java,multithreading,java-8,thread-safety,completable-future,Java,Multithreading,Java 8,Thread Safety,Completable Future,我不熟悉Java 8中的CompletableFuture,我想知道当我在回调中将结果设置为类成员属性,并在allOf().get()调用后尝试读取它们时,下面的代码段是否是线程安全的,为什么 public void newInit() throws ExecutionException, InterruptedException { CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> { retu

我不熟悉Java 8中的
CompletableFuture
,我想知道当我在回调中将结果设置为类成员属性,并在
allOf().get()
调用后尝试读取它们时,下面的代码段是否是线程安全的,为什么

public void newInit() throws ExecutionException, InterruptedException {
    CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> {
        return 1L;
    }).thenAccept(result -> {
        this.result1 = result;
    });
    CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> {
        return 2L;
    }).thenAccept(result -> {
        this.result2 = result;
    });
    CompletableFuture.allOf(cf1, cf2).get();
}

您的问题包含在
java.util.concurrent
包中定义的:

定义 在内存操作(如读取和写入共享变量)上的关系之前发生一个线程写入的结果如下 仅当写入 操作发生在读取操作之前。[…]

java.util.concurrent
中所有类的方法及其应用 子包将这些保证扩展到更高级别的同步。 特别是:

  • [……]
  • 未来
    表示的异步计算执行的操作发生在检索 通过另一个线程中的
    Future.get()
    生成结果
  • [……]

总之,您的
get()
调用保证了线程在执行后可以看到您的写入操作。

@didierrl我将在CompletableFuture.allOf方法之后读取值,它是线程安全的吗?