I would like to understand why CompletableFuture is thread-safe in this example.
Let's say I have this class:
public class A {
private Integer someInt = 3;
public A(final Integer someInt) {
this.someInt = someInt;
}
... setter and getter
}
and a CompletableFuture that will return an instance of A.
Then I have one thread that called get() and is waiting for the result. There is also another thread that will supply the result to the CompletableFuture by calling complete(new A(5)).
If you check the code for complete(T), it will call completeValue(T) which in turn will use UNSAFE.compareAndSwapObject(...) to set the result. If I'm not mistaken this will only publish the reference to instance A but it won't publish the reference to someInt inside A, so the thread that is waiting might not have the correct result.