Java Concurrent Collections and Virtual Threads
Two voters merge into one ConcurrentHashMap and get exactly 200,000 votes. A chef thread waits on a BlockingQueue until the waiter adds soup, salad and pasta. Then a virtual thread next to a platform one, and 20,000 waiting tasks that finish far sooner on virtual threads.
What you will learn
- Count safely from several threads with ConcurrentHashMap.merge
- Hand work from one thread to another with a BlockingQueue whose take waits
- Start a virtual thread and tell it apart from a platform thread
- Explain why virtual threads suit many tasks that mostly wait
Before you start
- Java ExecutorService and thread pools
- Java race conditions and synchronized
You don't always need your own locks. Java has a map and a queue that many threads can share safely, and virtual threads that are cheap enough to start one per task. Thread timings vary from run to run, so treat the times below as one run.
Two voters, one shared map
package org.studyeasy.s06l09;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Ex01_VoteCounter {
public static void main(String[] args) throws InterruptedException {
// one map, shared by all threads
Map<String, Integer> votes = new ConcurrentHashMap<>();
votes.put("yes", 0);
Runnable voter = () -> {
for (int i = 0; i < 100_000; i++) {
// old count + 1, done as ONE step
votes.merge("yes", 1, (old, one) -> old + one);
}
};
Thread emma = new Thread(voter);
Thread chris = new Thread(voter);
emma.start();
chris.start();
emma.join();
chris.join();
System.out.println("Expected: 200000");
System.out.println("Votes: " + votes.get("yes"));
}
}
Expected: 200000
Votes: 200000
A ConcurrentHashMap is made for many threads. merge("yes", 1, (old, one) -> old + one) reads the old count and writes the new one as a single step on that key, so a second voter's update waits its turn instead of overwriting. Write it as votes.put("yes", votes.get("yes") + 1) instead and it's get, then put: two steps, and the threads overwrite each other like the lost updates from before.
A chef who waits for orders
BlockingQueue<String> orders = new LinkedBlockingQueue<>();
Thread chef = new Thread(() -> {
System.out.println("Chef waits for orders");
try {
for (int i = 1; i <= 3; i++) {
// take() waits while the queue is empty
String dish = orders.take();
System.out.println("Chef cooks " + dish);
}
} catch (InterruptedException e) { }
});
chef.start();
String[] dishes = {"soup", "salad", "pasta"};
for (String dish : dishes) {
Thread.sleep(1000); // one new order each second
System.out.println("Waiter adds " + dish);
orders.put(dish);
}
Chef waits for orders
Waiter adds soup
Chef cooks soup
Waiter adds salad
Chef cooks salad
Waiter adds pasta
Chef cooks pasta
The chef asks for an order; the queue is empty, so take() waits. When the waiter (main) puts soup, take hands it straight over. One thread produces, another consumes, and the queue does the waiting for you. Swap take() for poll() and it never waits: it returns null at once, so the chef cooks null.
The same task on two kinds of thread
Runnable task = () -> {
Thread me = Thread.currentThread();
System.out.println(
me.getName() + " is virtual? " + me.isVirtual());
};
// a platform thread: the kind you already know
Thread emma = new Thread(task, "emma");
emma.start();
emma.join();
// a virtual thread: the same task
Thread oliver = Thread.ofVirtual().name("oliver").start(task);
oliver.join();
emma is virtual? false
oliver is virtual? true
A normal platform thread is a full operating-system thread, and the system sets aside memory for each one. A virtual thread (final since Java 21) is managed by Java and is cheap to make. A virtual thread doesn't keep the program alive, so without oliver.join() main may end first.
Behind the scenes, Java keeps a few platform threads called carriers. A virtual thread hops onto a free carrier to run, and when it waits (sleeping, or waiting on a network call), it steps off, leaving the carrier free for another.
20,000 tasks that only wait
// 20,000 tasks that each wait 1 second; returns the milliseconds taken
static long timeAll(ExecutorService executor) {
long start = System.currentTimeMillis();
for (int i = 1; i <= 20_000; i++) {
executor.submit(() -> {
try {
Thread.sleep(1000); // each task just waits
} catch (InterruptedException e) { }
});
}
executor.close(); // wait for every task
return System.currentTimeMillis() - start;
}
ExecutorService virtual =
Executors.newVirtualThreadPerTaskExecutor();
ExecutorService platform = Executors.newThreadPerTaskExecutor(
Thread.ofPlatform().factory());
virtual threads: 1106 ms
platform threads: 5777 ms
That's one real run; your times will differ with your computer. Both executors start a new thread per task. With virtual threads, the 20,000 tasks all wait together and finish in about a second, close to the 1-second sleep itself. With platform threads, each task is a real OS thread, and creating 20,000 of them takes much longer. A fixed pool of 100 would be worse still: only 100 run at a time, so roughly 200 seconds.
Recap
| Tool | Use it for |
|---|---|
ConcurrentHashMap.merge | many threads updating one map, each change in one step |
BlockingQueue.take | a consumer that waits for the next item |
Thread.ofVirtual().start(task) | a cheap thread for one task |
newVirtualThreadPerTaskExecutor() | many tasks that mostly wait |
Safe to share, cheap to start. That closes the concurrency section; next up are files and directories.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
