CompletableFuture, mutable objects and memory visibility

前端 未结 1 1801
南方客
南方客 2021-02-02 11:00

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 idea

1条回答
  •  天涯浪人
    2021-02-02 11:22

    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.

    0 讨论(0)
提交回复
热议问题