java - `Future<?>` 任务完成后检查字段是否安全?

标签 java concurrency future completable-future

检查 Future<?> 中执行的任务修改的字段是否安全?成功调用future.get()后?
(是否保证完成值设置,并且我看到新值?)

我会在调用 future.get() 的同一线程上检查该字段。 .

或者我应该只使用 future.get() 的返回值并且不应该期望它会像这样工作吗?

示例:

class MyData {
    private int a;

    public void setA(int a) { this.a = a; }
    public int getA() { return a; }
}

public class MainClass {
    public static void main(String[] args) {
        final Executor executor = Executors.newFixedThreadPool(15);

        final List<MyData> objects = Arrays.asList(new MyData(), new MyData() /* ... */);

        final Future<Void> future1 = CompletableFuture.supplyAsync(() -> { objects.get(0).setA(1); return null; }, executor);
        final Future<Void> future2 = CompletableFuture.supplyAsync(() -> { objects.get(1).setA(2); return null; }, executor);
        /* ... */

        a.get();
        b.get();
        /* ... */

        // Is it safe here to check the `a` field of the objects?
        assert objects.get(0).getA() == 1;
        assert objects.get(1).getA() == 2;
    }
}

最佳答案

Future 的 javadoc州

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.

get仅当相应的计算完成时才会返回(setA 调用和 return),该计算通过与任何代码的 happen-before 关系可见在调用get之后。您对 getA 的调用发生在 Future#get 之后,因此它将看到之前发生的 setA 的结果。

关于java - `Future<?>` 任务完成后检查字段是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323504/

相关文章:

java - 在哪里可以找到 JRE 的 native 库?

wcf - 在 2012 年,MSMQ 是否仍然对 WCF 中的排队调用有效?

c - 使用信号量在 Sleeping Barber 中打印

concurrency - rust future -cpupool : inconsistent behavior explanations

scala - Future[Any] 和 Future[_] 之间的区别

scala - Scala-ScheduledFuture

java - 我想一一打印我名字的字母

java - t :datatable apply css on row

java - 使用 CompletableFuture 重试逻辑

Java - 如何调试任务<Void>?