Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Thomas Hunter II, Bryan English

Rating No ratings yet

The nature of JavaScript is to be single threaded. This is reflected not only in libraries and applications, but also in online forum posts, books, and online documentation. Thanks to recent advancements in the platform—such as with web workers in the browser, worker_threads in Node.js, and the Atomics and SharedArrayBuffer objects—JavaScript engineers are able to build multi-threaded applications. These features will go down as being the biggest paradigm shift for the world's most popular programming language. Multithreaded JavaScript explores the various features that JavaScript runtimes have at their disposal for implementing multithreaded programming, using a spectrum of API reference material and high level programming patterns. • Learn what multithreaded programming is and how you can benefit from it • Understand the differences between a dedicated worker, a shared worker, and a service worker • Identify when and when not to use threads in an application • Orchestrate communication between threads by leveraging the Atomics object • Understand both the gains and pitfalls of using shared memory • Benchmark performance to learn when you'll benefit from multiple threads

AI Reading Assistant

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

AI guide
# Multithreaded JavaScript: Concurrency Beyond the Event Loop ## 【One-Line Pitch】 A practical guide to JavaScript's emerging multithreading capabilities—covering web workers, worker_threads, shared memory, and Atomics—for developers who want to break free from single-threaded constraints and build truly parallel applications in browsers and Node.js. ## 【Book Arc】 - **Opening (~0%–10%)**: Establishes the fundamental concepts of concurrency versus parallelism, explains why JavaScript's single-threaded nature has been a limitation, and introduces the core problem—how to achieve true parallel execution in a language designed without built-in threading support. - **Early (~10%–29%)**: Builds foundational knowledge through a C-based example (the "Happycoin" problem) that demonstrates threading concepts in a traditional language, then transitions to JavaScript's browser-based solutions, introducing the web worker API as the most approachable entry point. - **Middle (~29%–48%)**: Explores the full spectrum of browser worker types—dedicated workers, shared workers with their semipersistent state capabilities, and service workers for cache management—with practical examples showing how to implement each pattern and debug them using browser developer tools. - **Late (~48%–75%)**: Shifts to Node.js's worker_threads module, covering workerData for initialization, MessagePort for communication, and the Piscina library for building worker pools, with the Happycoin example revisited to demonstrate real performance gains. - **Ending (~75%–100%)**: Delves into shared memory programming with SharedArrayBuffer and TypedArrays, the Atomics API for safe data manipulation, and advanced topics like Atomics.waitAsync(), nondeterminism, and thread synchronization—culminating in a Conway's Game of Life example application. ## 【Key Takeaways】 - **Concurrency and parallelism are distinct concepts** (Early): Concurrency means overlapping execution time, while parallelism means simultaneous execution—parallelism is a subset of concurrency. Understanding this distinction is crucial for designing effective multithreaded applications. - **JavaScript's multithreading support comes from runtimes, not the language itself** (Early): Different implementations (V8 in Chrome, SpiderMonkey in Firefox, JavaScriptCore in Safari, and V8 in Node.js) each implement concurrency primitives differently, meaning a worker thread in Node.js is not the same as a web worker in a browser. - **Web workers offload CPU-intensive work to keep the UI responsive** (Early): By moving heavy computation off the main thread, the browser can dedicate more resources to rendering, resulting in a smoother user experience—the primary motivation for browser-based threading. - **Shared workers maintain semipersistent state across multiple windows** (Middle): Unlike dedicated workers, shared workers persist as long as at least one window is connected, enabling state sharing between browser tabs—but this state is lost when the final window closes. - **Service workers serve a different purpose entirely** (Middle): They're designed for cache management and offline functionality rather than general-purpose threading, and they can't communicate between normal and private browsing windows. - **Worker pools solve the overhead problem** (Late): Creating a worker thread has significant cost, so libraries like Piscina provide reusable pools that amortize this overhead across many tasks—the Happycoin example shows dramatic performance improvements with just four workers. - **Shared memory requires careful synchronization** (Late): SharedArrayBuffer and Atomics provide the tools for true shared memory programming in JavaScript, but they demand rigorous discipline—without proper synchronization, unpredictable and nondeterministic results occur. ## 【Reading Tips】 - **Skim the C examples in Chapter 1** (~10%–29%): They establish threading fundamentals that JavaScript later builds upon, but you can move quickly if you're already familiar with pthreads or threading concepts in general. - **Deep-read the browser worker chapters** (~29%–48%): The distinctions between dedicated, shared, and service workers are subtle and critical—pay special attention to the debugging techniques and the shared worker caching caveat. - **Focus on the Node.js worker_threads section** (~48%–75%): The Happycoin revisited example is the book's centerpiece for demonstrating real performance gains—make sure you understand the worker pool pattern with Piscina. - **The Atomics and shared memory chapters are the hardest part** (~75%–100%): Take your time with Atomics methods like compareExchange and waitAsync—these are the most error-prone APIs in the book, and the Conway's Game of Life example is worth building yourself. - **Run the code examples**: The book provides downloadable code samples, and the examples are designed to be run—you'll learn far more by executing the Happycoin benchmarks and worker demos than by just reading them. ## 【Coverage Limits】 The excerpts primarily cover the browser worker chapters and early Node.js material; the deepest shared memory and Atomics content is only partially represented in the sample, so readers should expect to spend significant time with the later chapters for full coverage. ##
Excerpt 1
57 MessagePort 58 Happycoin: Revisited 60 With Only the Main Thread 60 With Four Worker Threads 63 Worker Pools with Piscina 65 A Pool Full of Happycoins 69...
View in text
Page 19
program can continue executing. This interruption of other programs is not desirable, so eventually operating systems moved toward preemptive multitasking. I...
View in text
Excerpt 3
s beneficial for many reasons, but one that is particularly applicable to browsers is that, by offloading CPU-intensive work to a separate thread, the main t...
View in text
Excerpt 4
ache management of a web‐ site or a single page application. They are most commonly invoked when network requests are sent to the server, wherein an event ha...
View in text
Excerpt 5
e of the web worker classes you’ve been working with so far. Instead, the code instantiates a new RpcWorker class. This class is going to be defined soon. Af...
View in text
Excerpt 6
ar to what we did in C. We loop 10,000,000 times, getting a random number and checking if it’s a Happycoin. If it is, we print it out. Note that we’re not us...
View in text
Excerpt 7
tes that is stored on disk, or even in a computer’s memory, it’s a little ambiguous what the data means. For example, what might the hexadecimal value 0x54 (...
View in text
Excerpt 8
other thread will get the updated value of 1 or 2 returned. A timeline of how these operations work can be seen in Figure 4-2, with the CEX(oldExpectedValue,...
View in text
Tags
AI categories
Programming LanguageJavaScriptBackend
ISBN: 1098104439
Publisher: O'Reilly Media
Publish Year: 2021
Language: English
Pages: 200
File Format: PDF
File Size: 5.8 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…