Skip to main content

🧡 Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

πŸš€ “How are Virtual Threads different from Thread Pools?”
😡 “Are they OS threads or JVM threads?”
πŸ™ƒ “Should I still use CompletableFuture?”
🀯 “How do I even use them in real-time microservices?”

🧠 What are Virtual Threads?

Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel.

πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads.

🧠 What is the OS Kernel?

πŸ›️ OS Kernel = The Brain of the Operating System
It’s the core part of your OS (Windows, Linux, Mac) that:

  • Manages memory 🧠
  • Schedules threads πŸ•’
  • Talks to hardware πŸ’»
  • Handles I/O operations πŸ“¨

When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread.

πŸ–Ό️ Imagine This...


               ┌───────────────────────────┐
               │   Your Java Application   │
               └────────────┬──────────────┘
                            │
                            ▼
                ┌─────────────────────┐
                │     JVM (Java)      │
                └────────────┬────────┘
                             ▼
                    ┌────────────────┐
                    │   OS Kernel     │  <-- πŸ‘‘ THE BOSS
                    └────────────────┘

πŸ‘† In traditional threading, JVM tells the OS Kernel:
“Hey, I need a thread!”
The OS Kernel:
“Okay, here's an expensive, heavyweight OS thread πŸ‹️‍♂️.”

🧚 Virtual Threads: JVM says "No thanks!" to the Kernel

In Virtual Threads, the JVM says:

“I’ll handle my own threads inside me! I don’t need the OS kernel for each tiny task.”

So, the JVM runs its own mini scheduler, called the "user-mode scheduler", to manage thousands or even millions of tiny threads.

  • ✅ No OS-level thread for each Java task
  • ✅ No need to block real system threads for I/O
  • ✅ Just use a few carrier threads and juggle tasks smartly

🎨 Diagram: Virtual Threads vs Traditional Threads

Feature Traditional Threads πŸ‹️ Virtual Threads 🧚
Managed by OS Kernel πŸ–₯️ JVM Scheduler ☕
Memory per thread ~1MB stack ~few KB stack
Blocking I/O Expensive Cheap (handled async)
Thread creation Limited (few thousand max) Millions possible!
Uses Thread class? ✅ Yes ✅ Yes (surprise!)
Useful for CPU-bound 🧠 I/O-bound πŸ“¨

πŸ›️ Architecture View (Virtual Thread)


                ┌──────────────────────────────┐
                │        Application Code      │
                └──────────────────────────────┘
                          │
                          ▼
 Traditional:     ┌────────────┐
     ↳ Thread --> │ OS Thread  │ --> Expensive! πŸ”₯
                  └────────────┘

 Virtual:         ┌───────────────┐
     ↳ Thread --> │ JVM Scheduler │ --> Lightweight! ☁️
                  └───────────────┘

πŸ€” Are Virtual Threads Inside or Outside JVM?

➡️ Virtual Threads are purely JVM-level constructs.

They don’t map 1:1 to OS threads. Instead, JVM uses a small pool of carrier OS threads under the hood to run millions of virtual threads via scheduling.

πŸ“Œ OS thread ≠ Java thread anymore. JVM does the magic.

πŸ” Virtual Threads vs CompletableFuture

Feature Virtual Threads 🧚 CompletableFuture πŸš€
Programming model Imperative (normal Thread.sleep) Functional, async-style (thenApply)
Easy to debug? ✅ Super easy ❌ Stack traces can be complex
Use case Replace thread pools, simple code Reactive chains, parallel tasks
Scheduling Handled by JVM Uses thread pools (ForkJoinPool)
Exception handling Traditional try/catch Use .exceptionally, hard for freshers

πŸ‘‰ Think of Virtual Threads as: “Asynchronous made Synchronous”

πŸ”§ Real World Code Comparison

🚫 Traditional Thread Pool (Before Java 21)


ExecutorService executor = Executors.newFixedThreadPool(10);

executor.submit(() -> {
    // Some I/O task
    fetchDataFromDB();
});

✅ Virtual Threads (Java 21+)


ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

executor.submit(() -> {
    fetchDataFromDB(); // Looks blocking, but isn't costly
});

πŸŽ‰ No CompletableFuture, no callback hell. Just plain readable code!

πŸ”₯ Real-time Example: Spring Boot REST API

Let's say you’re building a REST API that calls DB + Redis + External API.

🧟‍♂️ ThreadPool Style:


@GetMapping("/user")
public CompletableFuture<User> getUser() {
    return CompletableFuture.supplyAsync(() -> userService.getUserDetails());
}

🧚 Virtual Thread Style:


@GetMapping("/user")
public User getUser() {
    return userService.getUserDetails(); // Blocking? Who cares. It’s virtual!
}

➡️ Benefit: No need to switch programming paradigm. Cleaner logs, easier debugging, fewer threads blocking.

❓ Why should I enable Virtual Threads for a normal REST call? It’s just a request/response, right?

It seems like a normal REST call is simple—but under the hood, it often involves:

  • ⏳ Calling external REST APIs
  • πŸ›’️ Querying databases
  • πŸ’Ύ Accessing caches like Redis

All of these operations are blocking I/O tasks. If you're using a fixed-size thread pool, threads doing these tasks will sit idle while waiting for responses—wasting system resources.

πŸ’‘ With Virtual Threads, the JVM can pause and resume these I/O tasks efficiently—freeing up the underlying OS threads for other work.

Conclusion: Even basic REST APIs benefit from Virtual Threads if they perform blocking I/O.

❓ Will my REST controller automatically run on a Virtual Thread?

πŸ›‘ No, not by default! REST controllers use platform threads (OS-backed) unless you explicitly configure Spring Boot to use Virtual Threads.

To enable them in Spring Boot 3.2 or later, use:

# application.yaml
server:
  virtual-threads:
    enabled: true

✅ Once enabled, all incoming HTTP requests will be handled using Virtual Threads under the hood—so your synchronous code remains clean and resource-efficient

🧠 What are Virtual Threads?

Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel.

πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads.

⚠️ Do's & Don'ts

  • ✅ Do use Virtual Threads for I/O-heavy apps (REST calls, DB queries)
  • ❌ Don’t use Virtual Threads if your logic is CPU-heavy (matrix multiplication etc.)
  • ✅ Do migrate ExecutorService to Executors.newVirtualThreadPerTaskExecutor()
  • ❌ Don’t manually .start() millions of new Thread() objects

πŸ§ͺ Sample Implementation


public class VirtualThreadDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

        for (int i = 0; i < 10000; i++) {
            executor.submit(() -> {
                System.out.println("Thread: " + Thread.currentThread());
                Thread.sleep(100); // This is okay!
                return null;
            });
        }

        executor.shutdown();
    }
}

☕ Run this and see 10,000 tasks running with just a few carrier threads behind the scenes!

πŸ›‘ What You Can’t Do

  • You can’t do CPU-heavy stuff with millions of threads
  • Virtual threads don’t help with deadlocks
  • You still need synchronization (they don’t magically fix shared state problems)

πŸ’‘ Interview Questions You May Face

Basic:

  • ❓ What is a Virtual Thread?
  • ❓ How does it differ from a traditional thread?
  • ❓ Is it inside the JVM or OS-level?
  • ❓ How do you create a Virtual Thread?

Intermediate:

  • ❓ How does Virtual Thread reduce memory usage?
  • ❓ Can we use Thread.sleep() inside Virtual Thread?
  • ❓ Compare Virtual Threads vs CompletableFuture.

Advanced:

  • ❓ Can I use Virtual Threads in Spring Boot today?
  • ❓ What happens if Virtual Threads do blocking DB calls?
  • ❓ Is Virtual Thread an alternative to Reactive Programming?

🎁 Wrapping Up

πŸ‘¨‍πŸ’» Virtual Threads are here to change the way Java handles concurrency.
They bring the simplicity of synchronous code with the power of async under the hood.

  • πŸ’₯ Replace ugly thread pool code
  • πŸ’₯ Ditch CompletableFuture chains
  • πŸ’₯ Write code like a boss — clean, readable, and millions of tasks without breaking the JVM

Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🌟 My Journey – From Zero to Senior Java Tech Lead 🌟

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. πŸ’― Sounds crazy? Let me take you back. πŸ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . πŸ§ͺ Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...