Future<?>成功调用后检查由 a 中执行的任务修改的字段是否安全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;
}
}
拉莫斯之舞
LEATH
相关分类