0% found this document useful (0 votes)
4 views11 pages

Java Virtual Threads

Java Virtual Threads, introduced in Project Loom and standardized in Java 21, are lightweight threads managed by the JVM that enable high-concurrency applications with minimal resource consumption. They improve scalability and resource utilization by allowing millions of threads to run efficiently, particularly for I/O-bound tasks, while simplifying concurrent programming. Key features include low memory usage, fast creation, and compatibility with existing Java APIs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Java Virtual Threads

Java Virtual Threads, introduced in Project Loom and standardized in Java 21, are lightweight threads managed by the JVM that enable high-concurrency applications with minimal resource consumption. They improve scalability and resource utilization by allowing millions of threads to run efficiently, particularly for I/O-bound tasks, while simplifying concurrent programming. Key features include low memory usage, fast creation, and compatibility with existing Java APIs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Virtual Threads – Detailed Notes

1. Introduction
Java Virtual Threads are lightweight threads introduced as part of Project Loom. They allow
developers to create and manage a very large number of concurrent tasks without the high
memory and scheduling costs associated with traditional platform threads.

Virtual threads simplify writing scalable concurrent applications by letting developers use the
familiar thread-per-task programming model without exhausting system resources.

They became a standard feature in Java 21 (LTS) after being introduced as a preview feature in
earlier Java versions.

2. What are Virtual Threads?


A Virtual Thread is a lightweight thread managed by the Java Virtual Machine (JVM) instead
of being directly managed by the operating system.

Unlike traditional threads, virtual threads are created, scheduled, and paused by the JVM. They
consume very little memory and can be created in very large numbers.

Definition

A Virtual Thread is a lightweight thread that enables high-concurrency applications by allowing


millions of threads to execute efficiently with minimal resource consumption.

3. Why Virtual Threads Were Introduced


Traditional Java threads are known as Platform Threads. Every platform thread maps directly
to one operating system thread.

Creating many platform threads results in:

• High memory usage


• Increased CPU overhead
• Slow context switching
• Limited scalability
For example, if a web server creates one platform thread for every client request, thousands of
simultaneous users can quickly exhaust available system resources.

Virtual Threads solve this problem by allowing the JVM to efficiently schedule lightweight
threads over a small pool of operating system threads.

4. Platform Threads vs Virtual Threads


Platform Threads Virtual Threads
Managed by Operating System Managed by JVM
Heavyweight Lightweight
High memory consumption Low memory consumption
Limited number of threads Millions of threads possible
Expensive creation Fast creation
Slower context switching Faster scheduling
Suitable for CPU-intensive tasks Best for I/O-intensive tasks

5. Architecture of Virtual Threads


The execution model is as follows:

Application


Virtual Threads


JVM Scheduler


Carrier (Platform) Threads


Operating System

Explanation

• Applications create Virtual Threads.


• The JVM scheduler manages these threads.
• Virtual Threads run on a smaller number of carrier threads (platform threads).
• When a virtual thread blocks on operations such as file or network I/O, the JVM can
unmount it from its carrier thread, allowing that carrier thread to execute another virtual
thread.

This improves resource utilization and scalability.

6. Features of Virtual Threads


• Lightweight and efficient
• Managed entirely by the JVM
• Low memory usage
• Fast creation and destruction
• Support millions of concurrent threads
• Simplify concurrent programming
• Fully compatible with existing Java APIs
• Reduce thread management complexity

7. Creating Virtual Threads


Java provides multiple ways to create Virtual Threads.

Method 1: Using [Link]()


public class Demo {

public static void main(String[] args) {

[Link](() -> {

[Link]("Virtual Thread Running");

});
}
}

Output

Virtual Thread Running

Method 2: Using Thread Builder


public class Demo {

public static void main(String[] args) {

Thread thread = [Link]()


.start(() -> {

[Link]("Hello");

});

}
}

Method 3: Creating an Unstarted Virtual Thread


Thread thread = [Link]()
.unstarted(() -> {

[Link]("Running");

});

[Link]();

8. Virtual Thread Lifecycle


A Virtual Thread follows a lifecycle similar to traditional threads.

NEW


STARTED


RUNNABLE


PARKED / BLOCKED / WAITING


RUNNABLE


TERMINATED

States

NEW
• Thread object is created.

RUNNABLE

• Ready to execute.

BLOCKED / WAITING

• Waiting for I/O, locks, or another thread.

TERMINATED

• Execution completes.

9. Executor Service with Virtual Threads


Java provides an Executor Service specifically designed for Virtual Threads.

import [Link].*;

public class Demo {

public static void main(String[] args) {

ExecutorService executor =
[Link]();

[Link](() -> {

[Link]("Task Executed");

});

[Link]();
}
}

Advantages

• Automatically creates a virtual thread for every task


• Simplifies concurrent programming
• Efficient resource utilization
• Easy integration with existing applications
10. Carrier Threads
Virtual Threads do not execute directly on the CPU.

Instead, they execute on Carrier Threads, which are normal platform threads managed by the
JVM.

Virtual Thread A
Virtual Thread B
Virtual Thread C


Carrier Thread


CPU

The JVM automatically switches Virtual Threads onto available carrier threads.

11. Scheduling of Virtual Threads


The JVM scheduler manages Virtual Threads.

It performs:

• Thread scheduling
• Suspension
• Resuming
• Context switching

Developers do not need to manually manage scheduling.

12. Blocking Behavior


Traditional Threads

Platform Thread


Blocked

When blocked, the operating system thread cannot execute another task.
Virtual Threads

Virtual Thread


Blocked


Released from Carrier Thread

The carrier thread becomes free to execute another virtual thread.

This significantly improves scalability.

13. Advantages of Virtual Threads


High Scalability

Applications can handle millions of concurrent tasks.

Better Resource Utilization

Fewer operating system threads are required.

Faster Thread Creation

Virtual Threads are inexpensive to create.

Simplified Programming

Developers can continue writing familiar sequential code while achieving high concurrency.

Lower Memory Consumption

Each virtual thread requires much less memory than a platform thread.

Better Performance for I/O

Ideal for:

• Web servers
• Database applications
• REST APIs
• Microservices
• Network programming

14. Limitations of Virtual Threads


Virtual Threads are not a solution for every problem.

Limitations include:

• CPU-intensive tasks gain little benefit.


• Some native libraries or legacy code may pin carrier threads.
• Excessive synchronization can reduce scalability.
• They do not make algorithms faster; they mainly improve concurrency for waiting tasks.

15. Virtual Threads vs Traditional Threads


Feature Traditional Thread Virtual Thread
Managed By Operating System JVM
Memory Usage High Low
Thread Creation Slow Fast
Scheduling OS Scheduler JVM Scheduler
Scalability Thousands Millions
Context Switching Expensive Efficient
Best For CPU-intensive work I/O-intensive work

16. Real-World Applications


Virtual Threads are useful in:

• Web servers
• RESTful services
• Database applications
• Cloud-native applications
• Banking systems
• Chat applications
• Online gaming servers
• File servers
• Network services
• Distributed systems

17. Best Practices


• Use Virtual Threads for tasks that spend time waiting (network, database, file I/O).
• Avoid long-running CPU-bound work in a large number of virtual threads.
• Use structured concurrency (where available) to organize related concurrent tasks.
• Minimize synchronized blocks and locks.
• Shut down executors after use.
• Continue following good exception-handling practices inside thread tasks.

18. Sample Program


import [Link].*;

public class VirtualThreadExample {

public static void main(String[] args) {

try (ExecutorService executor =


[Link]()) {

for (int i = 1; i <= 5; i++) {

int task = i;

[Link](() -> {

[Link](
"Task " + task +
" executed by " +
[Link]());

});
}
}
}
}

Sample Output
Task 1 executed by VirtualThread[#21]
Task 2 executed by VirtualThread[#22]
Task 3 executed by VirtualThread[#23]
Task 4 executed by VirtualThread[#24]
Task 5 executed by VirtualThread[#25]

(The order may vary because the tasks run concurrently.)

19. Differences Between newVirtualThreadPerTaskExecutor()


and Fixed Thread Pool
Fixed Thread Pool Virtual Thread Executor
Limited number of threads One virtual thread per task
Threads are reused New virtual thread for each task
Better for limited CPU work Better for large numbers of blocking tasks
Limited scalability Extremely high scalability

20. Frequently Asked Exam Questions


Short Questions

1. What is a Virtual Thread?


2. What is Project Loom?
3. Define a Carrier Thread.
4. State two advantages of Virtual Threads.
5. Differentiate between Platform Threads and Virtual Threads.
6. Which Java version introduced Virtual Threads as a standard feature?
7. Why are Virtual Threads considered lightweight?

Long Questions

1. Explain Virtual Threads with a suitable architecture diagram.


2. Compare Platform Threads and Virtual Threads.
3. Explain different methods of creating Virtual Threads with examples.
4. Describe the lifecycle of a Virtual Thread.
5. Explain the advantages, limitations, and applications of Virtual Threads.
6. Write a Java program using [Link]() and
explain its output.
Quick Revision
• Virtual Thread: A lightweight JVM-managed thread introduced through Project Loom.
• Standard Release: Java 21 (LTS).
• Managed By: JVM Scheduler.
• Runs On: Carrier (Platform) Threads.
• Best For: I/O-bound and highly concurrent applications.
• Benefits: Lightweight, scalable, low memory usage, fast creation, simple programming
model.
• Creation Methods: [Link](), [Link]().start(),
and [Link]().
• Key Idea: Virtual Threads allow applications to handle a massive number of concurrent
tasks efficiently while keeping code simple and readable.

You might also like