async/await and CompletableFuture: C# and Java

Both languages write an asynchronous call as a value that completes later, and both let the caller wait for several of them at once. C# has async and await in the language and Task in the library; Java has CompletableFuture in the library and no keyword for it, and since Java 21 it also has virtual threads. The task is three calls that each wait and return a name with their delay.

The task in C#

Three calls start before any is awaited, so their delays overlap; Task.WhenAll waits for all three and keeps the order of the array. A Stopwatch measures the elapsed time:

using System.Diagnostics; Console.WriteLine("async 1.0"); var watch = Stopwatch.StartNew(); var first = FetchAsync("a", 30); var second = FetchAsync("b", 10); var third = FetchAsync("c", 20); var results = await Task.WhenAll(first, second, third); watch.Stop(); Console.WriteLine($"results {string.Join(", ", results)}"); Console.WriteLine($"order kept {results[0] == "a30" && results[2] == "c20"}"); Console.WriteLine($"over 40 ms {watch.ElapsedMilliseconds >= 40}"); Console.WriteLine($"under 100 ms {watch.ElapsedMilliseconds < 100}"); static async Task<string> FetchAsync(string name, int delay) { await Task.Delay(delay); return $"{name}{delay}"; }

dotnet run
echo "status: $?"

async 1.0
results a30, b10, c20
order kept True
over 40 ms True
under 100 ms True
status: 0

The same task in Java

The same three calls as CompletableFuture values from supplyAsync, CompletableFuture.allOf for the wait, and then the virtual threads of Java 21 for two more calls:

import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class AsyncConcurrency { public static void main(String[] args) throws Exception { System.out.println("async 1.0"); long start = System.nanoTime(); var first = fetch("a", 30); var second = fetch("b", 10); var third = fetch("c", 20); CompletableFuture.allOf(first, second, third).join(); long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); System.out.println("results " + List.of(first.join(), second.join(), third.join())); System.out.println("order kept " + (first.join().equals("a30") && third.join().equals("c20"))); System.out.println("over 40 ms " + (elapsed >= 40)); System.out.println("under 100 ms " + (elapsed < 100)); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { var one = executor.submit(() -> "one"); var two = executor.submit(() -> "two"); System.out.println("virtual " + one.get() + " " + two.get()); } } static CompletableFuture<String> fetch(String name, int delay) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(delay); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return name + delay; }); } }

javac -g -d out AsyncConcurrency.java
java -cp out AsyncConcurrency
echo "status: $?"

async 1.0
results [a30, b10, c20]
order kept true
over 40 ms true
under 100 ms false
virtual one two
status: 0

What differs

The next page is about the value that both languages treat as a mistake: the null reference.

Exercises

  1. Change the C# delays so that the third call finishes first and check the order of the results.
  2. Use CompletableFuture.thenCombine in Java to add the three names instead of joining them.
  3. Run each program three times and compare the elapsed flags.
  4. Replace Task.Delay with Thread.Sleep and explain what happens to the pool.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Task.WhenAll return?

    Answer

    A task that completes when all of them do, with the results in the order of the array

    The measured results keep the order a, b, c.

  2. Which Java type plays the role of a task?

    Answer

    CompletableFuture

    The page builds three of them with supplyAsync.

  3. What does this program print? static async Task<string> Fetch(string name, int delay) { await Task.Delay(delay); return $"{name}{delay}"; } var results = await Task.WhenAll(Fetch("a", 30), Fetch("b", 10), Fetch("c", 20)); Console.WriteLine(string.Join(", ", results));

    Answer

    a30, b10, c20

    The C# array keeps the order of the tasks.

  4. Why did the first Java run print under 100 ms false?

    Answer

    The first run of a JVM pays for class loading and pool startup

    A later run of the same program printed true.

  5. What does this program print? var tasks = new[] { Task.Delay(10), Task.Delay(20), Task.Delay(30) }; await Task.WhenAll(tasks); Console.WriteLine(tasks.Length);

    Answer

    3

    Three tasks are awaited by WhenAll.

  6. What does await do to the thread?

    Answer

    It gives the thread back while the task is incomplete

    The three delays overlap on a small thread pool.

  7. What does this program print? var watch = System.Diagnostics.Stopwatch.StartNew(); await Task.WhenAll(Task.Delay(10), Task.Delay(20)); watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds < 100);

    Answer

    True

    The elapsed time of three overlapping waits is under a hundred milliseconds.

  8. What is a virtual thread?

    Answer

    A thread scheduled by the JVM on a small number of carrier threads

    Java 21 starts one per task with a virtual-thread executor.

  9. What does this program print? var values = new[] { 1, 2, 14 }; Console.WriteLine(values.Sum());

    Answer

    17

    The first measured results run under the delays of the page.

  10. What does CompletableFuture.allOf need before a join?

    Answer

    Nothing: it is the wait itself, and join reads the futures after it

    The page calls join on allOf and then joins the three futures.

The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev

Banner image