Concurrency and virtual threads
Servers handle thousands of requests at once; apps download files while staying responsive. Concurrency means doing several things at the same time. Java has had threads since version 1.0, and Java 21 added virtual threads, which make highly concurrent code simple again.
Concurrent programs can print in a different order each run. The examples here are written so that their output is predictable (they wait for results before printing), which is good practice anyway.
Threads
A thread is an independent path of execution. Every program starts with one (the main thread), and you can start more:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
System.out.println("worker: working…");
sleep(200);
System.out.println("worker: done");
});
worker.start(); // runs concurrently with main
System.out.println("main: started the worker");
worker.join(); // wait for it to finish
System.out.println("main: worker finished, exiting");
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}main: started the worker worker: working… worker: done main: worker finished, exiting
(The first two lines can appear in either order: both threads run at once. Here the worker is slower to start, so main usually prints first.)
The danger: race conditions
When threads share data, updates can collide. count++ looks like one step, but it's three (read, add, write), and two threads can interleave them:
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static int unsafeCount = 0;
static final AtomicInteger safeCount = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
unsafeCount++; // not atomic: updates get lost
safeCount.incrementAndGet(); // atomic: never loses an update
}
};
Thread a = new Thread(task);
Thread b = new Thread(task);
a.start(); b.start();
a.join(); b.join();
System.out.println("safe: " + safeCount.get());
System.out.println("unsafe is correct? " + (unsafeCount == 200_000));
}
}safe: 200000 unsafe is correct? false
The unsafe counter ends up below 200,000, and by a different amount every run. These bugs are hard to reproduce, so prevent them by design.
Ways to stay safe
| Tool | Use |
|---|---|
| Don't share mutable state | Give each task its own data; return results instead (best option) |
Immutable objects (records, final fields) |
Safe to share freely |
AtomicInteger, AtomicLong… |
Single counters and flags |
ConcurrentHashMap, CopyOnWriteArrayList |
Thread-safe collections |
synchronized / ReentrantLock |
Make a block of code run in one thread at a time |
import java.util.concurrent.ConcurrentHashMap;
class Inventory {
private int stock = 10;
synchronized boolean buy(int qty) { // only one thread at a time runs this
if (stock < qty) return false;
stock -= qty;
return true;
}
synchronized int stock() { return stock; }
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Inventory inv = new Inventory();
ConcurrentHashMap<String, Integer> sold = new ConcurrentHashMap<>();
Thread[] buyers = new Thread[20];
for (int i = 0; i < buyers.length; i++) {
buyers[i] = new Thread(() -> {
if (inv.buy(1)) sold.merge("units", 1, Integer::sum);
});
buyers[i].start();
}
for (Thread t : buyers) t.join();
System.out.println("sold " + sold.get("units") + ", left " + inv.stock());
}
}sold 10, left 0
Twenty buyers competed for ten items: exactly ten sales, never an oversell.
Executors: thread pools
Creating threads by hand doesn't scale. An ExecutorService manages a pool of threads and gives you Futures, handles to results that will be ready later:
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
static int slowSquare(int n) {
try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); }
return n * n;
}
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) { // closes the pool afterwards
List<Future<Integer>> futures = List.of(1, 2, 3, 4).stream()
.map(n -> pool.submit(() -> slowSquare(n)))
.toList();
int total = 0;
for (Future<Integer> f : futures) total += f.get(); // get() waits for each result
System.out.println("total = " + total);
}
long ms = System.currentTimeMillis() - start;
System.out.println("ran in parallel: " + (ms < 300));
}
}total = 30 ran in parallel: true
Four 100 ms tasks finished in about 100 ms instead of 400 ms, because they ran at the same time.
CompletableFuture: composing async work
CompletableFuture chains asynchronous steps without blocking, like JavaScript promises:
import java.util.concurrent.CompletableFuture;
public class Main {
static String fetchUser(int id) { pause(100); return "user" + id; }
static int fetchOrderCount(String user) { pause(100); return user.length(); }
static void pause(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
public static void main(String[] args) {
CompletableFuture<String> summary = CompletableFuture
.supplyAsync(() -> fetchUser(42)) // runs in the background
.thenApply(user -> user + " has " + fetchOrderCount(user) + " orders")
.exceptionally(err -> "lookup failed: " + err.getMessage());
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> { pause(100); return 2; });
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> { pause(100); return 3; });
CompletableFuture<Integer> both = a.thenCombine(b, Integer::sum); // run both, combine results
System.out.println(summary.join());
System.out.println(both.join());
}
}user42 has 6 orders 5
Virtual threads (Java 21+)
Traditional threads are platform threads: each one is backed by an operating system thread and uses about a megabyte of memory, so a server can only have a few thousand. Virtual threads are lightweight threads managed by the JVM. You can have millions, and when one waits (for a database, an HTTP call, a sleep), the JVM parks it and uses the OS thread for something else.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1)); // simulates a slow I/O call
return i;
}));
} // waits for all 10,000 tasks
long seconds = (System.currentTimeMillis() - start) / 1000;
System.out.println("10,000 tasks that each waited 1 second finished in about " + seconds + "s");
}
}10,000 tasks that each waited 1 second finished in about 1s
Ten thousand blocking tasks, written in simple, straightforward style, all waiting at once. With a pool of 200 platform threads, the same work would take about 50 seconds.
Key points:
- Write normal, blocking code (
Thread.sleep, JDBC, HTTP clients). Virtual threads make it scale. No callbacks needed. - Use them for I/O-bound work (web servers, calling APIs and databases). For CPU-bound work, a fixed pool sized to your CPU cores is still right.
- Frameworks support them directly; for example, Spring Boot:
spring.threads.virtual.enabled=true. - Start one directly with
Thread.ofVirtual().start(runnable)orThread.startVirtualThread(runnable).
Parallel streams
For CPU-heavy work on large collections, adding .parallel() splits a stream across cores:
import java.util.stream.LongStream;
public class Main {
static boolean isPrime(long n) {
if (n < 2) return false;
for (long d = 2; d * d <= n; d++) if (n % d == 0) return false;
return true;
}
public static void main(String[] args) {
long count = LongStream.rangeClosed(1, 2_000_000).parallel().filter(Main::isPrime).count();
System.out.println(count + " primes up to 2,000,000");
}
}148933 primes up to 2,000,000
Only use it for genuinely CPU-heavy work on big inputs, with no shared mutable state. For small collections, the coordination overhead makes it slower.
Practice
- Start 5 threads that each add their number (1 to 5) to a shared
AtomicInteger, join them all, and print the total (15). - Use a fixed thread pool to "download" 6 files (simulate each with
Thread.sleep(200)), and measure the total time with 1, 3 and 6 threads. - Rewrite exercise 2 with
Executors.newVirtualThreadPerTaskExecutor()and 1,000 files.
1.Why can two threads running count++ on a shared int lose updates?
2.What does future.get() do?
3.What are virtual threads best suited for?