<code>class Y { private int value; private List<String> names; public Y() { this.names = new ArrayList<>(); } public void setValue(int value) { this.value = value; } public int getValue() { return value; } public void addName(String name) { this.names.add(name); } public List<String> getNames() { return names; } } class X { private Y y; public void setY(Y y) { this.y = y; } public Y getY() { return y; } } public class Main { public static void main(String[] args) { X x = new X(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { Y newY = new Y(); newY.setValue(42); newY.addName("Alice"); newY.addName("Bob"); x.setY(newY); // Update the y field of x }); future.join(); // Wait for the CompletableFuture to complete // Will the main thread always see the updated y field? System.out.println("Value: " + x.getY().getValue()); // Should print 42 System.out.println("Names: " + x.getY().getNames()); // Should print [Alice, Bob] } } </code>

问题描述 投票:0回答:1

Collections.synchronizedList

来实现这一点?
在我的卑鄙看法中,
join()

方法可确保在主线程进行之前完成

CompletableFuture
任务执行的所有操作。这意味着
CompletableFuture
任务对
join()
任务进行的字段或对象的任何更新都将在

join()

返回后可见主线程。但是我不确定这些字段的内存可见性。他们可能看不到

注:
此示例是对更复杂情况的简化反映。在实践中,我知道我可以在完成后直接设置X对象(例如,x = future.join())。但是,我的实际用例涉及嵌套对象和跨多个线程共享状态,这就是为什么我专注于现场可见性和线程安全性。
    
package java.util.concurrentdocs

仅在读取操作之前,仅当写入操作发生时,一个线程的写入结果才能看到另一个线程的读取。

如果工人偶然进行的操作 - 从

CompletableFuture.join
java multithreading thread-safety completable-future java-memory-model
1个回答
0
投票

我在官方文档中没有发现Future.get

CompletableFuture
.

共享相同的保证。 但是,在

https://bugs.openjdk.org/browse/jdk-8292365
中有评论,并建议记录保证:

由{@code future}
-happen-before

Actions{@code future.get()},{@code future.result.resultnow()或{@code future.exceptionnow()},在另一个线程中。 通过{@code ploteabefuture.getnow}或{@code plotebefuture.join}。

这倾向于我认为
CompletableFuture.join
Future.get
。 并且在文档中指出,Future.gethappen-before
在被称为以前的动作以下操作:

luther.get()在另一个线程中取回结果后的动作以后发生的异步计算所采取的措施。
不幸的是,没有关于

-happen-before保证CompletableFuture.join

的明确声明,但是有一张票可以添加:
https://bugs.openjdk.org/browse/browse/jdk-8292365..

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.