Concurrency question

Arkadiusz Gasiński jigga at jigga.pl
Thu Mar 21 10:02:54 UTC 2024


Hi there,

I realize this mailing list is not intended for general concurrency-related
discussions, however, I'll still give it a shot as there are a lot of
concurrency experts subscribed to this list.

Please redirect me to a more suitable mailing list, if this message is
unnecessary noise.

I had a discussion recently about a piece of code that's semantically
equivalent to the code snippet below:

public class ListDemo {
    public static void main(String[] args) throws Exception {
        final var list = new ArrayList<Integer>();
        try(var executor = Executors.newSingleThreadExecutor()) {
            final var futures = IntStream.iterate(1, i -> ++i)
                .limit(1_000_000)
                .parallel() // a little randomness
                .mapToObj(i -> (Supplier<Integer>) () -> {
                    list.add(i);
                    return i;
                })
                // all tasks are supplied to the single-threaded executor
                .map(supplier -> CompletableFuture.supplyAsync(supplier,
executor));
            // await completion
            CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new
)).get();
            // use the list
            System.out.println(list.size() == 1_000_000);
        }
    }
}

My question is: will all changes (writes) made to the list declared at the
start of the main method be visible in the main thread after the
ComplietableFuture.allOf(...).*get*() call returns.

>From the Future
<https://docs.oracle.com/en%2Fjava%2Fjavase%2F21%2Fdocs%2Fapi%2F%2F/java.base/java/util/concurrent/Future.html>
javadocs we have this one sentence:

Memory consistency effects: Actions taken by the asynchronous computation
> *happen-before*
> <https://docs.oracle.com/en%2Fjava%2Fjavase%2F21%2Fdocs%2Fapi%2F%2F/java.base/java/util/concurrent/package-summary.html#MemoryVisibility> actions
> following the corresponding Future.get() in another thread.


And due to that, my understanding is that all writes to the list happen
before the subsequent (after get returns) reads from the list, and no
matter what thread reads the list, it will ALWAYS observe all changes made
to the list.

Is my understanding correct? If not, please let me know.

Thanks,
Arek
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20240321/903c5023/attachment.htm>


More information about the loom-dev mailing list