DEV Community

Dev Sk
Dev Sk

Posted on

How Java Virtual Threads Work?

Virtual Threads are lightweight threads introduced in Java 19 (Preview) and Java 21 (Stable). They allow Java to create millions of threads efficiently, helping handle concurrent tasks without wasting memory or CPU.

Virtual Threads do not map 1:1 to OS Threads and do not replace the original Platform Threads. The Platform Threads are backed by the OS Threads and are sometimes also known as Carrier Threads in this context.

Think of the Platform Threads as a small group of workers, and Virtual threads as tasks. With Virtual threads, tasks are given to workers only when needed, allowing one worker to handle thousands of tasks efficiently.

Here’s how Virtual Threads work:

Virtual Threads run on top of Platform Threads. The JVM schedules them onto a small number of Platform Threads.

When a Virtual Thread starts, the JVM assigns it to a normal OS-backed Platform Thread.

Virtual Threads can also handle CPU-intensive work, but their real advantage is in scenarios with a high number of I/O-bound or concurrent tasks.

If the Virtual Thread performs a blocking operation (like I/O, database call, sleep, etc.), the JVM unmounts it from the Platform Thread. However, this does not block the underlying OS Thread as such.

The Platform thread is freed up to handle another Virtual Thread.

When the blocking operation finishes, the Virtual Thread is rescheduled on any available Platform thread

technology #innovation #future #techupdate" #technews #futuretech #innovation #AI #automation #techtrends #digitaltransformation #fullstackdeveloper

reactdeveloper

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay