Is it thread-safe to set value to class member property in CompletableFuture callback?
Is it thread-safe to set value to class member property in CompletableFuture callback?
I am new to CompletableFuture
in Java 8 and I wonder whether the following code snippet is thread-safe when I set the result to class member properties in a callback, and try to read them after the allOf().get()
call, and why?
CompletableFuture
allOf().get()
public void newInit() throws ExecutionException, InterruptedException {
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> {
return 1L;
}).thenAccept(result -> {
this.result1 = result;
});
CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> {
return 2L;
}).thenAccept(result -> {
this.result2 = result;
});
CompletableFuture.allOf(cf1, cf2).get();
}
1 Answer
1
Your question is covered by the Memory Consistency Properties defined on the java.util.concurrent
package:
java.util.concurrent
Chapter 17 of the Java Language Specification defines the
happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are
guaranteed to be visible to a read by another thread only if the write
operation happens-before the read operation. […]
The methods of all classes in java.util.concurrent
and its
subpackages extend these guarantees to higher-level synchronization.
In particular:
java.util.concurrent
Future
Future.get()
So to summarize, your get()
call guarantees that your writes will be visible to the thread after it performs it.
get()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
@DidierL I will read the values after CompletableFuture.allOf method, is it thread-safe?
– Chuck
Jun 28 at 6:25