CompletableFuture, mutable objects and memory visibility

青春壹個敷衍的年華 提交于 2020-07-04 07:36:10

问题


I'm trying to understand how CompletableFuture in Java 8 interacts with the Java memory model. It seems to me that for programmer sanity, the following should ideally hold true:

  1. Actions in the thread that completes a CompletableFuture happen-before any completions dependent stages are executed
  2. Actions in the thread that registers a completion creates a dependent stage happen-before the completion dependent stage is executed

There's a note in java.util.concurrent documentation saying that:

Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.

Which would suggest that the first property is true, as long as the thread that completes the future executes the completion dependent stage or submits it to an Executor. On the other hand, after reading CompletableFuture documentation I'm not so sure about that:

Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method.

Which brings me to my questions:

  1. Are the two hypothetical properties above true or not?
  2. Is there any specific documentation anywhere about the presence or lack of memory visibility guarantees when working with CompletableFuture?

Addendum:

In the way of a concrete example, consider this code:

List<String> list1 = new ArrayList<>();
list1.add("foo");

CompletableFuture<List<String>> future =
        CompletableFuture.supplyAsync(() -> {
            List<String> list2 = new ArrayList<>();
            list2.addAll(list1);
            return list2;
        });

Is it guaranteed that adding "foo" to list1 is visible to the lambda function? Is it guaranteed that adding list1 to list2 is visible to the dependent stages of future?


回答1:


  1. Yes, both of your hypotheses are true. The reason is, that all of the *Async() methods in CompletableFuture will use a java.util.concurrent.Executor to make the asynchronous call. If you don't provide one, this will either be the common pool or an Executor that creates a new thread for each task (in case you restrict the size of the common pool to 0 or 1) or a user-provided Executor. As you already found out, the documentation of the Executor says:

    Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

    So in your example, it is guaranteed that "foo" is part of list1 in your lambda and that list2 is visible in subsequent stages.

  2. This is basically covered by the documentation of Executor.



来源:https://stackoverflow.com/questions/34427972/completablefuture-mutable-objects-and-memory-visibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!