Thuta Learning
Java
AdvancedProgrammingBeginner

Concurrency & Virtual Threads

JavaLesson 3040 min

What you'll walk away with

  • Explain how virtual threads differ from platform threads and which workloads they suit
  • Use Executors.newVirtualThreadPerTaskExecutor() in try-with-resources to run one thread per task
  • Collect results with Future.get() and extract a task's failure from ExecutionException
  • Protect a shared counter with AtomicInteger to avoid a race condition
  • Make output deterministic even though threads finish in any order

Explain it simply

Explain it simply

Imagine a restaurant with one waiter who stands at the kitchen door waiting for each dish: every other table waits too. A thread is like a waiter, and with several of them work can happen at the same time. Ordinary platform threads, however, are like expensive staff, and you cannot hire thousands of them.

Virtual threads are waiters who give their seat at the counter back while they wait for the kitchen, so a few seats (CPU cores) can serve thousands of waiters. They suit programs that spend most of their time waiting on networks, databases or files.

Problem → Why → Solution

The problem: threads updating one counter

The program below starts 10,000 threads and each one runs count++. The answer should be 10000, but a run can print a smaller number such as 9,8xx, and because it does not happen every time it is even more dangerous. count++ is not one step but three, read, add one and write back, so two threads can read the same value and one update overwrites the other.

There is a second bug: main() never waits for the threads to finish before printing count, so it can read the value while some threads are still running.

Main.java
public class Main {
  static int count = 0;

  public static void main(String[] args) {
    for (int i = 0; i < 10_000; i++) {
      Thread.ofVirtual().start(() -> count++);   // read-add-write race
    }
    System.out.println(count);   // no join: threads may still be running
  }
}

Why does this happen?

The scheduler decides when each thread runs and pauses, and you cannot control it. When several threads modify the same mutable data without synchronization, the result depends on timing, which is called a race condition. The fix is to protect shared state with an AtomicInteger, a lock or a concurrent collection, or better to share nothing and have each task return its result to be combined in one place, and then to wait for every thread with join or Future.get() before reading the result.

Core concept: platform threads and virtual threads

Each ordinary Java thread, a platform thread, is paired one-to-one with an operating system thread and reserves a large amount of memory for its stack. Creating thousands of them gets expensive in memory and context switching, so servers share a small thread pool. While a request waits on the database its thread sits blocked doing nothing, and once the pool is full new requests queue up.

Virtual threads, finalized in Java 21 by JEP 444, are managed by the JVM itself. A running virtual thread is mounted on one of a few platform threads called carriers; when it blocks, in Thread.sleep() or socket I/O for example, it unmounts and frees the carrier for another virtual thread. That makes virtual threads cheap enough to create by the thousands or even millions, so you can keep writing simple blocking-style code with one thread per task.

Virtual threads do not make code faster; they let more waiting work happen at once. CPU-heavy calculations will not run faster than your number of cores allows. Do not pool virtual threads: create a new one for every task, and use a Semaphore when you need to cap how many tasks hit a resource such as a database at the same time.

Race conditions happen with virtual threads exactly as with platform threads, so shared state still needs protecting. In Java 21, a virtual thread that blocks inside a synchronized block stays pinned to its carrier, so ReentrantLock is the better choice around long waits. Later JDK releases relaxed this limitation, so check the release notes for the version you use.

Mental model: submit, wait, collect in order
  1. One virtual thread per task
  2. Blocking frees the carrier thread
  3. Keep Futures in submission order
  4. get() each result or failure
  5. Close the executor to wait for all

Threads finish in random order; the order of your saved Futures, not of completion, should decide the output.

General pattern

java
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
  List<Future<Result>> futures = new ArrayList<>();
  for (Input input : inputs) {
    futures.add(executor.submit(() -> blockingWork(input)));
  }
  for (Future<Result> f : futures) {
    use(f.get());              // throws ExecutionException if the task failed
  }
}                              // close() waits for every submitted task

Thread t = Thread.ofVirtual().start(() -> work());
t.join();

Create a virtual-thread-per-task executor in try-with-resources, submit each task and keep its Future in a list. get() waits for the result and rethrows a task's exception wrapped in ExecutionException. Without an executor, Thread.ofVirtual().start() starts a single thread and join() waits for it.

Example: fetching three prices concurrently

This example runs three tasks at once on virtual threads, each faking a network call with Thread.sleep(200) and reporting through isVirtual() that it ran on a virtual thread. Each task takes 200 ms, but because they wait at the same time the total is close to 200 ms rather than 600 ms. Results are printed in the order of the Future list, so the output is identical on every run.

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String fetchPrice(String product) throws InterruptedException {
    Thread.sleep(200);                       // pretend this is a slow network call
    boolean virtual = Thread.currentThread().isVirtual();
    return product + " = " + product.length() * 10 + " (virtual: " + virtual + ")";
  }

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    List<String> products = List.of("apple", "kiwi", "banana");
    List<Future<String>> futures = new ArrayList<>();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (String product : products) {
        futures.add(executor.submit(() -> fetchPrice(product)));
      }
      for (Future<String> future : futures) {
        System.out.println(future.get());    // waits; prints in submission order
      }
    }
    System.out.println("All " + futures.size() + " tasks finished");
  }
}

Code breakdown

  1. Line 10Thread.sleep(200); // pretend this is a slow network call

    While the virtual thread sleeps it is unmounted from its carrier, so the carrier can keep running other tasks.

  2. Line 19try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {

    An executor that creates a new virtual thread for every submitted task. ExecutorService has been AutoCloseable since Java 19, so it works in try-with-resources.

  3. Line 21futures.add(executor.submit(() -> fetchPrice(product)));

    submit() starts the task immediately and returns a Future at once. The lambda returns a value and may throw, so it is a Callable<String>, and the for-each variable product is effectively final, so the lambda may use it.

  4. Line 24System.out.println(future.get()); // waits; prints in submission order

    get() blocks until that task is done. Only the main thread prints, in list order, so whichever task finishes first the output is always apple, kiwi, banana.

  5. Line 26}

    At the end of the try block executor.close() is called automatically and waits for every submitted task, which is why "All 3 tasks finished" always comes last.

You should see
apple = 50 (virtual: true)
kiwi = 40 (virtual: true)
banana = 60 (virtual: true)
All 3 tasks finished

Fixing the race with AtomicInteger

Replace the counter from the problem section with an AtomicInteger and wait for every thread with join(), and the result is always correct. incrementAndGet() performs read, add and write as one indivisible (atomic) operation, so no update is lost. Notice also that nothing prints from inside the threads; the main thread prints once, after all of them have finished.

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    AtomicInteger hits = new AtomicInteger();
    List<Thread> threads = new ArrayList<>();

    for (int i = 0; i < 1_000; i++) {
      Thread t = Thread.ofVirtual().start(() -> hits.incrementAndGet());
      threads.add(t);
    }
    for (Thread t : threads) {
      t.join();                              // wait for every thread
    }
    System.out.println("Hits: " + hits.get());
  }
}

Ten thousand blocking tasks

The program below runs 10,000 tasks that each sleep for one second on virtual threads. With a pool of ten threads that work would take around 1,000 seconds. With virtual threads they all wait at the same time and finish within a few seconds on a typical machine; the exact time depends on the machine, so the program only prints whether it took less than ten seconds.

Main.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
  public static void main(String[] args) {
    AtomicInteger done = new AtomicInteger();
    long start = System.nanoTime();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (int i = 0; i < 10_000; i++) {
        executor.submit(() -> {
          Thread.sleep(1_000);               // 10,000 tasks blocking for 1 second
          return done.incrementAndGet();
        });
      }
    }                                        // close() waits for all of them

    long seconds = (System.nanoTime() - start) / 1_000_000_000;
    System.out.println("Completed: " + done.get());
    System.out.println("Took less than 10 s: " + (seconds < 10));
  }
}

In real projects

Where this shows up in real projects

Web servers usually handle each request on its own thread. A request spends most of its time waiting on database queries, HTTP calls to other microservices and cache lookups, so running requests on virtual threads means far less queueing for a full thread pool. Spring Boot 3.2 and later can move request handling onto virtual threads with the spring.threads.virtual.enabled=true setting; check the documentation for your version for the details.

Calling three services at once for a dashboard's profile, order history and recommendations and combining them through Futures, or a batch job downloading hundreds of files, uses exactly the pattern in this lesson. Such systems cap concurrent calls to an external API with a Semaphore, log each task's failure from its ExecutionException and carry on with the remaining results. Structured concurrency (StructuredTaskScope), a preview feature in Java 21, aims to make cancellation and failure handling for a group of tasks clearer; check its status in the release notes before using it in production.

Common mistakes

Common mistakes

1. Pooling virtual threads

Writing Executors.newFixedThreadPool(10, Thread.ofVirtual().factory()) treats virtual threads as scarce like platform threads and throws away their benefit. Give every task a new thread, and limit access to a resource with a Semaphore when you need to.

2. Believing a thread-safe collection fixes every race

Even with a ConcurrentHashMap, another thread can slip in between the two steps of if (!map.containsKey(k)) map.put(k, v);. Each method is thread-safe on its own, but the combination is not. Use atomic methods such as putIfAbsent(), computeIfAbsent() or merge().

3. Printing directly from racing threads

When every task calls System.out.println() itself, the output order changes from run to run and makes logs and tests hard to follow. Have tasks return their results and let the main thread print them in Future order.

4. Ignoring ExecutionException from get()

Future.get() rethrows a task's exception wrapped in ExecutionException. If you never call get(), you never learn the task failed. Use e.getCause() to reach the underlying exception.

Mini challenge

Mini challenge: load user profiles concurrently

Load four user ids concurrently on virtual threads. Id 3 throws, and the tasks finish in a different order from the ids. Print the output in id order, show each failure with its message, and print how many loads succeeded.

  • Use newVirtualThreadPerTaskExecutor() in try-with-resources
  • Store the Futures in a LinkedHashMap<Integer, Future<String>> that keeps id order
  • Catch ExecutionException and show getCause().getMessage()
  • Never print from inside a task; the output must be identical on every run
Main.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String loadUser(int id) throws InterruptedException {
    Thread.sleep(50L * (4 - id % 4));        // later ids finish first
    // TODO: throw IllegalStateException("user 3 not found") for id 3
    return "user-" + id;
  }

  public static void main(String[] args) throws InterruptedException {
    List<Integer> ids = List.of(1, 2, 3, 4);
    Map<Integer, Future<String>> futures = new LinkedHashMap<>();
    // TODO: submit loadUser(id) for every id on a virtual-thread executor
    // TODO: print "<id> -> <result>" or "<id> -> failed: <message>" in id order
    // TODO: print "Loaded <n> of <total>"
  }
}

Expected: The program should print this on every run: 1 -> user-1 2 -> user-2 3 -> failed: user 3 not found 4 -> user-4 Loaded 3 of 4

Show hint

Submit the tasks inside the try block and loop over the Futures after it: close() has already waited for every task, so get() returns immediately. getCause() on the ExecutionException is the IllegalStateException the task threw.

Show solution
Main.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String loadUser(int id) throws InterruptedException {
    Thread.sleep(50L * (4 - id % 4));        // later ids finish first
    if (id == 3) {
      throw new IllegalStateException("user " + id + " not found");
    }
    return "user-" + id;
  }

  public static void main(String[] args) throws InterruptedException {
    List<Integer> ids = List.of(1, 2, 3, 4);
    Map<Integer, Future<String>> futures = new LinkedHashMap<>();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (int id : ids) {
        futures.put(id, executor.submit(() -> loadUser(id)));
      }
    }                                        // close() waits for every task

    int loaded = 0;
    for (Map.Entry<Integer, Future<String>> entry : futures.entrySet()) {
      try {
        System.out.println(entry.getKey() + " -> " + entry.getValue().get());
        loaded++;
      } catch (ExecutionException e) {
        System.out.println(entry.getKey() + " -> failed: " + e.getCause().getMessage());
      }
    }
    System.out.println("Loaded " + loaded + " of " + ids.size());
  }
}

Quick quiz 1 / 3

Which workload benefits most from virtual threads?

Quick quiz 2 / 3

A task threw IllegalStateException. What happens when you call its Future.get()?

Quick quiz 3 / 3

1,000 virtual threads each run total += 1 on a static int, and the program prints it after joining them all. What is printed?

What to remember

  • Threads that share mutable data without synchronization race, so use AtomicInteger, locks, or results returned from tasks.
  • Java 21 virtual threads release their carrier when they block, which makes them cheap for thousands of I/O-bound tasks, but they do not speed up CPU work.
  • Use newVirtualThreadPerTaskExecutor() in try-with-resources, whose close() waits for every task, and never pool virtual threads.
  • Collect results and ExecutionExceptions with Future.get(), and print from the main thread in Future order.

JEP 444: Virtual Threads — OpenJDK

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.