使用CompletableFuture的thenAccept进行可见性保证。

huangapple 未分类评论50阅读模式
英文:

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&lt;Void&gt; cf1 = CompletableFuture.supplyAsync(() -&gt; &quot;Hello&quot;)
        .thenAccept(sampleClass::setMember1);

CompletableFuture&lt;Void&gt; cf2 = CompletableFuture.supplyAsync(() -&gt; &quot; World&quot;)
        .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.

huangapple
  • 本文由 发表于 2020年5月3日 21:49:32
  • 转载请务必保留本文链接:https://java.coder-hub.com/61575531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定