Concurrency, executors & virtual threads
Write thread-safe code and use executors, CompletableFuture and virtual threads.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
Concurrency lets a program do several things at once, but shared mutable state can cause race conditions. Java offers locks, atomics, executors, CompletableFuture and, since Java 21, cheap virtual threads.
Explained simply
A thread is a path of execution inside your program. With several threads, your program can do several things at once: serve many web requests, or download files while it computes. Modern CPUs have many cores, and threads are how Java uses them.
The danger is shared data. If two threads change the same variable at the same time, updates can be lost, a bug called a race condition. It may appear once in a thousand runs, which makes it very hard to find. Protecting shared data is the core skill of concurrency.
Java gives you several tools. synchronized and locks let only one thread at a time into a critical section. Atomic classes and concurrent collections do safe updates without you writing locks. Executors manage a pool of threads so you just submit tasks.
Java 21 added virtual threads. They are so cheap that you can start one per task, even a million of them. They shine when tasks spend most of their time waiting, for example on a database or an HTTP call, which is exactly what most backend code does.
Press Play on a diagram to walk through it one step at a time.
- 1NEW
Thread object created, start() not yet called
- 2RUNNABLE
Running or ready to run on a CPU
- 3BLOCKED / WAITING
Waiting for a lock, join, sleep or I/O
- 4Back to RUNNABLE
Lock acquired or wait finished
- 5TERMINATED
run() finished or threw an exception
- One OS thread each
- About 1 MB stack each
- Thousands at most
- Pool them with fixed executors
- Scheduled by the JVM
- Very cheap to create
- Millions possible
- Great for blocking I/O tasks
- 1supplyAsync(user)
Starts the user call on an executor
- 2supplyAsync(orders)
Starts the orders call at the same time
- 3thenCombine
Builds a Profile when both are done
- 4orTimeout(2 s)
Fails the future if it is too slow
- 5exceptionally
Falls back to an empty profile
- 6join()
Waits for the final result
- One variable
- Lock-free compare-and-set
- Counters, flags, references
- LongAdder for hot counters
- Several variables changed together
- One thread at a time
- Keep the critical section short
- Lock lets you time out
- Shared maps, queues, lists
- ConcurrentHashMap merge and compute
- BlockingQueue for producer-consumer
- No external locking needed
In depth
Visibility and the Java Memory Model
Races are not the only problem. Without coordination, one thread may not even see another thread's write, because CPUs and the JIT compiler keep values in caches and registers and may reorder instructions. A classic bug: a worker loops while (running), another thread sets running = false, and the worker never stops.
The Java Memory Model defines happens-before rules that guarantee visibility. Marking the flag volatile fixes the example: every write to a volatile field is visible to later reads of it. But volatile does not make count++ atomic. Releasing a lock happens-before the next acquisition of the same lock, so data written inside synchronized is seen by the next thread that enters. Thread.start() and Thread.join() also create these edges.
- volatile: visibility and ordering, not atomicity
- Unlock happens-before the next lock on the same monitor
- Everything before start() is visible to the new thread
- Immutable objects with final fields are safe to share
synchronized, ReentrantLock and deadlock
synchronized is the simplest lock: only one thread at a time can run code synchronized on the same object, and the lock is released automatically, even on an exception. ReentrantLock does the same job with more control: tryLock(1, TimeUnit.SECONDS) gives up instead of waiting forever, lockInterruptibly can be cancelled, and Conditions let threads wait for a signal. You must call unlock() in a finally block. ReadWriteLock allows many readers or one writer.
Deadlock happens when two threads each hold a lock the other needs, so both wait forever. The standard cure is a global lock order: always take locks in the same order, for example by account id. A thread dump (jstack or jcmd Thread.print) reports Java-level deadlocks directly.
- Thread A to Lock X: A takes X1A takes X
- Thread B to Lock Y: B takes Y2B takes Y
- Thread A to Lock Y: A waits for Y3A waits for Y
- Thread B to Lock X: B waits for X4B waits for X
- Lock X to Thread A: Nobody can move: deadlock5Nobody can move: deadlock
Atomics and concurrent collections
AtomicInteger, AtomicLong and AtomicReference use a CPU instruction called compare-and-set (CAS): update the value only if it still equals what I read, otherwise retry. No thread ever blocks. Under very heavy contention, LongAdder is faster for counters because it spreads updates over several cells and sums them when read.
ConcurrentHashMap lets many threads read and write without locking the whole map. But two safe calls in a row are not one safe call: if (!map.containsKey(k)) map.put(k, v) is a check-then-act race. Use the atomic methods instead: putIfAbsent, computeIfAbsent, compute and merge. map.merge(word, 1, Integer::sum) is a thread-safe counter per key. CopyOnWriteArrayList suits lists that are read constantly but rarely changed, such as listeners.
- counter.incrementAndGet() is atomic
- map.computeIfAbsent(k, x -> new ArrayList<>()) is atomic per key
- Collections.synchronizedMap locks the whole map for every call
Executors and CompletableFuture
Creating a platform thread per task is expensive, so you usually submit tasks to an ExecutorService. Executors.newFixedThreadPool(8) keeps 8 threads. submit returns a Future, and future.get() blocks until the result is ready. Always shut an executor down; since Java 19 it implements AutoCloseable, so try-with-resources waits for tasks and closes it.
CompletableFuture lets you describe async steps instead of blocking. supplyAsync starts work; thenApply transforms the result; thenCompose chains another async call; thenCombine joins two independent futures; allOf waits for many; exceptionally and handle deal with errors; orTimeout fails the future if it is too slow. Without an executor argument, async methods run on the shared ForkJoinPool.commonPool(), which is sized for CPU work. Pass your own executor for blocking I/O.
How virtual threads work
A virtual thread is a Java object scheduled by the JVM, not the operating system. The JVM runs it on a small pool of carrier threads, normally one per CPU core. When a virtual thread blocks on I/O, such as a socket read, the JVM unmounts it, saving its small stack on the heap, and the carrier picks up another virtual thread. Your code stays simple and blocking, yet one server can have hundreds of thousands of requests in flight.
Rules of thumb: do not pool virtual threads; create one per task. Limit access to scarce resources with a Semaphore or a connection pool instead. Avoid huge ThreadLocal caches, since you may have millions of threads. Before Java 24, blocking inside synchronized pinned the carrier; Java 24 removed that limitation. In Spring Boot 3.2+, spring.threads.virtual.enabled=true switches request handling to virtual threads.
- 1Virtual threads
Millions possible, one per task
- 2JVM scheduler
Mounts and unmounts them as they block
- 3Carrier threads
A few platform threads, about one per core
- 4OS threads
Scheduled by the kernel
- 5CPU cores
Where code actually runs
Learn it in 6 short steps
About 1h 20m each. Track them with a timer in your plan.
- 1Create threads and runnables~1h 20m
- 2Prevent races with synchronized and locks~1h 20m
- 3Use atomic and concurrent collections~1h 20m
- 4Run tasks with ExecutorService~1h 20m
- 5Chain async work with CompletableFuture~1h 20m
- 6Try virtual threads in Java 21~1h 20m
Key points
- A race condition happens when threads read and write shared state without coordination.
- Use synchronized, locks, atomics or concurrent collections to protect shared state.
- ExecutorService reuses threads; always shut it down or use try-with-resources.
- Virtual threads suit I/O-bound work; they do not make CPU-bound work faster.
Key terms
Tap a card to flip it. 0/6 known
Examples
AtomicInteger counter = new AtomicInteger();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++) {
ex.submit(() -> { counter.incrementAndGet(); });
}
} // close() waits for all submitted tasks
System.out.println(counter.get()); // always 1000
CompletableFuture.supplyAsync(() -> 42)
.thenApply(x -> x * 2)
.thenAccept(System.out::println); // 84With a plain int counter++ the total could be less than 1000.
Calling two services in parallel with a timeout
A profile page needs the user and their orders from two slow services. Called one after the other, they take 300 ms plus 400 ms. Step 1: start both with supplyAsync on an executor meant for I/O. Step 2: thenCombine builds the Profile when both finish, so the wait is about 400 ms. Step 3: orTimeout fails the future after 2 seconds. Step 4: exceptionally returns a fallback instead of an error. Note that orTimeout does not cancel the underlying calls; set timeouts on the HTTP clients too.
ExecutorService io = Executors.newVirtualThreadPerTaskExecutor();
CompletableFuture<User> user =
CompletableFuture.supplyAsync(() -> userClient.get(id), io);
CompletableFuture<List<Order>> orders =
CompletableFuture.supplyAsync(() -> orderClient.forUser(id), io);
Profile profile = user
.thenCombine(orders, Profile::new)
.orTimeout(2, TimeUnit.SECONDS)
.exceptionally(ex -> Profile.empty(id))
.join();Producer and consumer with a BlockingQueue
One thread reads jobs and another processes them at its own speed. Step 1: create a bounded ArrayBlockingQueue with room for 100 jobs. Step 2: the producer calls put, which waits when the queue is full, so memory cannot explode. Step 3: the consumer calls take, which waits when the queue is empty, so it never spins. Step 4: a special STOP message, often called a poison pill, tells the consumer to finish. Step 5: on InterruptedException, restore the interrupt flag instead of ignoring it.
BlockingQueue<String> queue = new ArrayBlockingQueue<>(100);
Thread producer = Thread.ofPlatform().start(() -> {
try {
for (int i = 0; i < 1_000; i++) queue.put("job-" + i); // waits if full
queue.put("STOP");
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = Thread.ofPlatform().start(() -> {
try {
String job;
while (!(job = queue.take()).equals("STOP")) process(job); // waits if empty
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});Quick reference
- volatile gives visibility, not atomicity: volatile count++ is still a race
- Always unlock a ReentrantLock in a finally block
- Take multiple locks in one global order to avoid deadlock
- Use map.merge(k, 1, Integer::sum) for thread-safe counting per key
- try (var ex = Executors.newFixedThreadPool(4)) { ... } waits and closes (Java 19+)
- CompletableFuture async methods default to ForkJoinPool.commonPool()
- Do not pool virtual threads; limit concurrency with a Semaphore
- jcmd PID Thread.print dumps all threads and reports deadlocks
Common mistakes
- Using count++ on a shared int; it is not atomic.
- Forgetting to shut down an executor, which keeps the JVM alive.
- Taking two locks in different orders in different threads, causing deadlock.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Start 4 threads that each increment a shared counter 10,000 times. Show that a plain int gives wrong totals and an AtomicInteger always gives 40,000.
- Exercise 2medium
Sum the squares of 1 to 1,000,000 using a fixed pool of 4 threads, splitting the range into 4 Callable tasks.
- Exercise 3hard
Run 1,000 tasks on virtual threads, but allow at most 10 of them to call a slow API at the same time.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many threads should a thread pool have?
- For CPU-bound work, about the number of cores (Runtime.getRuntime().availableProcessors()). For I/O-bound work you need many more, which is where virtual threads are simpler than tuning a big pool.
- Should I still use synchronized in 2026?
- Yes, for short critical sections it is simple and fast, and since Java 24 it no longer pins virtual threads. Use ReentrantLock when you need timeouts, interruptible waits or several conditions.
- Does Spring Boot support virtual threads?
- Yes. From Spring Boot 3.2 on Java 21+, setting spring.threads.virtual.enabled=true makes Tomcat and Spring's task executors use virtual threads.
- What is the difference between a Future and a CompletableFuture?
- A Future only lets you block with get() or cancel. A CompletableFuture can also be completed manually and lets you chain, combine and handle errors without blocking.