Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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.

Many virtual threads wait in a pool above a few platform threads called carriers. A virtual thread hops onto a free carrier to run, and when it starts waiting, such as during sleep, it steps off and frees the carrier for another virtual thread. virtual threads: thousands carriercarriercarrier (free) A waiting virtual thread steps off its carrier, freeing it for another.
Many cheap virtual threads share a few platform carriers.

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

ToolUse it for
ConcurrentHashMap.mergemany threads updating one map, each change in one step
BlockingQueue.takea 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.

Keep going in Java · 73 of 79

Previous
Java Locks, Deadlock and tryLock
Next post
Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Two voters, one shared map
  • A chef who waits for orders
  • The same task on two kinds of thread
  • 20,000 tasks that only wait
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.