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
- await is a keyword and the compiler turns the method into a state machine; join and thenApply are methods on a value. The C# code reads top to bottom, and the Java code reads as a chain or as blocking calls.
- A C# Task is already running when it is returned; a Java CompletableFuture from supplyAsync is the same. A CompletableFuture that nobody composed is also a task that nobody waits for, which is why allOf is needed before the join.
- The results keep their order in both: WhenAll returns an array in the order of the tasks, and the Java page joins each future in the order it was created. Neither order is a promise of completion; it is a promise of the list.
- The first run of the Java program printed under 100 ms false and a later run printed true: the first run of a JVM pays for loading its classes and starting its common pool, and the C# process paid the same cost before the Stopwatch started. A timing of a first call is a timing of the runtime, not of the call.
- Virtual threads are the Java 21 answer to the cost of a blocking call on a pool thread: Executors.newVirtualThreadPerTaskExecutor() starts one per task and the JVM schedules them on the carrier threads. C# does not need them for this shape, because an await on a real asynchronous call does not hold a thread at all; a blocking call in a C# task does hold one.
The next page is about the value that both languages treat as a mistake: the null reference.
Exercises
- Change the C# delays so that the third call finishes first and check the order of the results.
- Use CompletableFuture.thenCombine in Java to add the three names instead of joining them.
- Run each program three times and compare the elapsed flags.
- 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.
-
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.
-
Which Java type plays the role of a task?
Answer
CompletableFuture
The page builds three of them with supplyAsync.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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