检查 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/