英文:
Visibility guarantee with CompletableFuture's thenAccept
问题
我试图理解CompletableFuture
是否提供任何可见性保证。
假设我有一个名为SampleClass
的类,类似于以下内容:
public class SampleClass {
private String member1;
private String member2;
// 获取器、设置器和构造函数;
}
然后我执行以下操作:
SampleClass sampleClass = new SampleClass();
CompletableFuture<Void> cf1 = CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(sampleClass::setMember1);
CompletableFuture<Void> cf2 = CompletableFuture.supplyAsync(() -> " World")
.thenAccept(sampleClass::setMember2);
cf1.join();
cf2.join();
// sout(sampleClass);
现在,我想要理解在sout
语句中,是否有可能出现一个或两个成员未被初始化的情况?
基本上,在这里CompletableFuture
是否提供了任何可见性保证?(我印象中CompletableFuture
没有提供这样的保证,上述代码是有问题的。)
我已经阅读了这个问题,但我认为那不是我需要的内容。
英文:
I'm trying to understand if there are any visibility-guarantees provided by CompletableFuture
.
Suppose I've a class called SampleClass
which is something like the following:
public class SampleClass {
private String member1;
private String member2;
// getters, setters and constructor;
}
And I do something like this:
SampleClass sampleClass = new SampleClass();
CompletableFuture<Void> cf1 = CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(sampleClass::setMember1);
CompletableFuture<Void> cf2 = CompletableFuture.supplyAsync(() -> " World")
.thenAccept(sampleClass::setMember2);
cf1.join();
cf2.join();
// sout(sampleClass);
Now, I want to understand that in the sout
statement, can there be a case when one or both the members is/are not initialized?
Basically is there any visibility-guarantee that's provided by CompletableFuture
in here? (I'm under the impression that there's no such guarantee provided by CompletableFuture
and the above code is broken.)
I've already gone through this question but I think it's not what I need.
专注分享java语言的经验与见解,让所有开发者获益!
评论