JvJava
AdvancedLesson 14 of 16

Concurrency & Virtual Threads – Java

Threads, ExecutorService, CompletableFuture, atomics and virtual threads (Java 21).

Concurrency uses several threads at the same time. Do not start threads by hand, but through an ExecutorService (thread pool). You get results through Future. Since Java 19, ExecutorService is AutoCloseable and at the end of try-with-resources waits for all tasks.

import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (var pool = Executors.newFixedThreadPool(4)) {
            List<Future<Integer>> futures = new ArrayList<>();
            for (int i = 1; i <= 5; i++) {
                int n = i;
                futures.add(pool.submit(() -> n * n));
            }
            for (var f : futures) System.out.println(f.get());   // 1 4 9 16 25
        }
    }
}

CompletableFuture allows asynchronous pipelines without blocking: chain tasks (thenApply), combine them (thenCombine) and handle errors (exceptionally).

var preis = CompletableFuture.supplyAsync(() -> 100.0);
var rabatt = CompletableFuture.supplyAsync(() -> 0.2);

var endpreis = preis
        .thenCombine(rabatt, (p, r) -> p * (1 - r))
        .thenApply(p -> "Final price: " + p)
        .exceptionally(ex -> "Error: " + ex.getMessage());
System.out.println(endpreis.join());        // Final price: 80.0

Shared mutable data needs protection. count++ is not atomic (read, increment, write). Use AtomicInteger, synchronized or locks – better still: immutable data and ConcurrentHashMap.

import java.util.concurrent.atomic.AtomicInteger;

var zaehler = new AtomicInteger();
Runnable job = () -> { for (int i = 0; i < 100_000; i++) zaehler.incrementAndGet(); };

Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start(); t2.start();
t1.join();  t2.join();
System.out.println(zaehler.get());          // always 200000

Virtual threads (Java 21, Project Loom) are extremely lightweight threads managed by the JVM. Blocking code (network, database) then no longer blocks an expensive operating-system thread – you can easily start tens of thousands at once and still write simple, sequential code.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        int nr = i;
        executor.submit(() -> {
            Thread.sleep(java.time.Duration.ofSeconds(1));   // blocks only the virtual thread
            return nr;
        });
    }
}   // waits for all of them; total duration about 1 second

Thread.startVirtualThread(() -> System.out.println("Hello from a virtual thread"));
WarningVirtual threads help with I/O-heavy tasks, not with pure computational load (for that, the number of CPU cores remains decisive). Do not pool virtual threads – create a new one for each task.