Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: A. N. M. Bazlur Rahman

Rating No ratings yet

Welcome to the future of Java. With this book, you'll explore the transformative world of Java 21's key feature: virtual threads. Remember struggling with the cost of thread creation, encountering limitations on scalability, and facing difficulties in achieving high throughput? Those days are over. This practical guide takes you from Java 1.0 to the cutting-edge advancements of Project Loom. You'll learn more than just theory. Author A N M Bazlur Rahman equips you with a toolkit for taking real-world action. Take a deep dive into the intricacies of virtual threads and complex topics such as ForkJoinPool, continuation, rate limiting, debugging, and monitoring. You'll not only learn how they work, but you'll also pick up expert tips and tricks to help you master these concepts. And you'll learn about structured concurrency and scoped values—critical skills for building Java applications that are scalable and efficient. • Get an in-depth understanding of virtual threads • Understand the implementation of virtual thread internals • Gain performance improvement in blocking operations • Learn why structured concurrency is beneficial • Know where to use scoped value • Understand the relevance of reactive Java with the advent of virtual threads A N M Bazlur Rahman is a software engineer with over a decade of experience in Java and related technologies. A speaker at various international conferences and Java user groups, his talks often focus on specialized topics such as concurrency and virtual threads.

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
# Modern Concurrency in Java: Virtual Threads, Structured Concurrency, and Beyond ## 【One-Line Pitch】 A practical, hands-on guide for experienced Java developers who want to master Java 21's virtual threads, structured concurrency, and scoped values—the tools that finally solve the decades-old problems of thread exhaustion, blocking I/O, and complex lifecycle management. If you've struggled with thread pool tuning or callback-heavy asynchronous code, this book shows you a simpler, more scalable path forward. ## 【Book Arc】 - **Opening (~0%–9%)**: Sets the stage by explaining why Project Loom matters—the historical pain points of Java concurrency (expensive threads, scalability limits, low throughput) and what virtual threads promise to fix. The author positions this as a practical resource for developers who already know traditional concurrency tools like Thread, ExecutorService, and ReentrantLock. - **Early (~9%–25%)**: Builds the foundation by tracing Java's concurrency evolution from Java 1.0's Thread class through ExecutorService, Fork/Join Pool, and CompletableFuture. Includes a concrete demonstration of thread limits (the author's test program hits ~16,000 threads before OutOfMemoryError) and shows how parallel execution improves performance (1.66x speedup in the credit calculation example). - **Early (~25%–34%)**: Introduces virtual threads as the solution to platform thread limitations. Shows how CompletableFuture's composability, while an improvement, still has drawbacks—and how virtual threads integrate seamlessly with existing codebases (just swap in `Executors.newVirtualThreadPerTaskExecutor()`). Covers environment setup with JDK 21 and SDKMAN. - **Middle (~34%–44%)**: Dives into virtual thread internals—how they're mounted and unmounted on carrier threads, how blocking operations are handled intelligently, and the updated Thread API (isVirtual(), threadId(), deprecated unsafe methods). Demonstrates creating 10,000 virtual threads with ease, explaining the scalability through Little's Law. - **Middle (~44%–47%)**: Addresses the critical practical concern that unlimited concurrency creates new problems—specifically, how to protect downstream resources (like databases) that can't handle unlimited load. Introduces rate limiting with semaphores as the essential mechanism for resource-aware concurrency. ## 【Key Takeaways】 - **Platform threads are a scarce resource** (Early): A simple test program reveals the hard limit—around 16,000 threads before OutOfMemoryError on typical systems. This scarcity is the root cause of thread pool tuning pain and why virtual threads matter. - **Java's concurrency evolution followed a clear progression** (Early): From Thread and Runnable (Java 1.0) → ExecutorService and Fork/Join Pool → CompletableFuture (Java 8) → virtual threads (Java 21). Each step solved specific problems but introduced new complexities—CompletableFuture improved composability but added callback-heavy complexity. - **Virtual threads are drop-in replacements for platform threads** (Early): The killer feature is seamless integration—existing ExecutorService code works with just one line change: `Executors.newVirtualThreadPerTaskExecutor()`. No rewrites, no new paradigms to learn, just instant scalability. - **Virtual threads handle blocking operations intelligently** (Middle): When a virtual thread blocks on I/O, it's unmounted from its carrier thread, freeing that carrier to run other virtual threads. This is the fundamental mechanism that makes millions of concurrent threads feasible. - **The Thread API has been modernized** (Middle): New methods like `isVirtual()` and `threadId()` (replacing deprecated `getId()`), plus duration-based `join()` and `sleep()`. Unsafe methods (stop(), suspend(), resume()) now throw UnsupportedOperationException—a long-overdue cleanup. - **Unlimited concurrency requires rate limiting** (Middle): Virtual threads remove the natural throttle that thread pools provided. Without explicit rate-limiting mechanisms (like semaphores), you risk overwhelming downstream services like databases. This is the new discipline developers must learn. - **Structured concurrency simplifies lifecycle management** (Middle): By treating related tasks as a single unit of work, structured concurrency reduces the burden of manual thread management, cancellation logic, and error handling—promoting a more declarative programming style. ## 【Reading Tips】 - **Skim the historical chapters (0–25%)** if you're already comfortable with Java concurrency basics—the key insight is the progression and the thread limit demonstration, not the code examples themselves. - **Deep-read the virtual thread internals section (~34–44%)**: Understanding mounting/unmounting on carrier threads is essential for debugging and performance tuning. This is where the book's real value lies. - **Pay special attention to the rate-limiting chapter (~44–47%)**: This is the most practical, production-ready advice in the book—the semaphore-based approach to protecting downstream resources is directly applicable to real systems. - **Have JDK 21 installed and ready**: The book is hands-on; you'll get the most value by running the examples, especially the 10,000-virtual-thread demonstration and the credit calculation performance comparisons. - **If you're new to concurrency fundamentals**, the author explicitly recommends reading *Java Concurrency in Practice* by Brian Goetz first—this book assumes you already know Thread, ExecutorService, and synchronization. ## 【Coverage Limits】 The excerpts cover the opening through the rate-limiting section (~47% of the book). The guide does not cover the later chapters on structured concurrency in depth, scoped values, debugging/monitoring virtual threads, or the relationship between reactive Java and virtual threads—these topics are mentioned but not explored in the available material. ##
Page 7
. . . . . . . . . . . . . ix 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
View in text
Excerpt 2
va platform, and a Java developer needs to understand them. The Genesis of Java 1.0 Threads Java 1.0 was released in 1996 and came with built-in support for ...
View in text
Excerpt 3
ities(person)); executor.submit(this::importantWork); return calculateCredits(assetsFuture.get(), liabilitiesFuture.get()); } } Replace any...
View in text
Excerpt 4
ying database may not be able to handle that many requests. Before virtual threads, the thread pool helped us limit requests without the need to implement ad...
View in text
Excerpt 5
r, potentially leading to more scalable designs. Monitoring Now that we understand the limitations of virtual threads, it’s clear they arise mainly from two ...
View in text
Excerpt 6
ool usually maintains a fixed or bounded number of threads, and thread creation and termination are less dynamic. On the other hand, ForkJoin Pool can adapti...
View in text
Excerpt 7
a parent task has several dependent subtasks, each running on a different thread. If the parent task terminates unexpectedly, its subtasks continue to execut...
View in text
Excerpt 8
scope.join(); log("... Scope joined successfully."); // Only reachable if join() succeeds return new ProductInfo(productTask.get(), reviewsTask....
View in text
Tags
AI categories
JavaProgramming LanguageBackend
ISBN: 1098165411
Publish Year: 2025
Language: English
Pages: 337
File Format: PDF
File Size: 4.5 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Generating text preview…