Virtual Threads
- 3.1 Motivation for Virtual Threads
- 3.2 Virtual Thread Execution Model
- 3.3 Using Thread Class to Create Virtual Threads
- 3.4 Using Thread Builders to Create Virtual Threads
- 3.5 Using Thread Factory to Create Threads
- 3.6 Using Thread Executor Services
- 3.7 Scalability of Throughput with Virtual Threads
- 3.8 Best Practices for Using Virtual Threads
- Review Questions
Chapter Topics
What virtual threads are and how they compare to platform threads.
How virtual threads are executed.
Creating and using virtual threads.
Using virtual thread executors to run tasks.
Best practices for using virtual threads.
Prerequisites
Understanding how platform threads are executed.
Understanding the thread lifecycle.
Creating and using platform threads.
Using executor services to run tasks.
Java SE 21 Developer Professional Exam Objectives |
|
[8.1] Create both platform and virtual threads. Use both Runnable and Callable objects, manage the thread lifecycle, and use different Executor services and concurrent API to run tasks. |
Only virtual threads are covered in this chapter. |
Introduction of virtual threads promises to facilitate building very high-throughput concurrent applications that employ the one-thread-per-task paradigm. These lightweight threads are under the regime of the JVM, and not the operating system. In this chapter we cover what virtual threads are, explain their high-throughput execution model, create and use them to run tasks, compare them to platform threads, and provide best practices for using them. Most importantly, we need hardly learn a new API to utilize them.
Before going forward, it is highly recommended to have a sound understanding of the traditional concurrency model based on platform threads as outlined in the prerequisites at the start of this chapter.
3.1 Motivation for Virtual Threads
The concurrency model in Java has traditionally centered around platform threads—threads that are scheduled by the operating system and mapped to operating system (OS) threads in order for them to execute Java code.
Concurrent applications based on one-thread-per-task paradigm strive to increase their throughput—that is, increase the number of tasks that can be done concur-rently—by requiring evermore platform threads. However, constraints on the number of platform threads that can be created and managed is often the bottleneck when it comes to scalability in concurrent applications. The constraints can be due to limitations imposed by the hardware, the operating system, or the sheer size of memory that would be required to handle vast number of platform threads. One-thread-per-task style of developing high-throughput concurrent applications with platform threads therefore becomes infeasible.
