Multithreaded JavaScript

Concurrency Beyond the Event Loop

I co-authored a book with Bryan English titled Multithreaded JavaScript! It's currently available for purchase online and in book stores.

Multithreaded JavaScript Cover
Multithreaded JavaScript Cover

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

Table of Contents

  • Intro
    • What are Threads?
    • Single Threaded JavaScript
    • Hidden Threads
    • Threads in C
  • Browser
    • Dedicated Workers
    • Shared Workers
    • Service Workers
    • Message Passing Abstractions
  • Node.js
    • Before We Had Threads
    • The worker_threads Module
    • Happycoin: Revisited
    • Worker Pools with Piscina
  • Shared Memory
    • Intro Shared Memory
    • SharedArrayBuffer and TypedArrays
    • Atomic Methods for Data Manipulation
    • Atomicity Concerns
    • Data Serialization
  • Advanced Shared Memory
    • Atomics Methods for Coordination
    • Timing and Non-Determinism
    • Example Application
    • Atomics and Events
  • Multithreaded Patterns
    • Thread Pool
    • Mutex: A Basic Lock
    • Streaming Data with Ring Buffers
    • Actor Model
  • WebAssembly
    • Your First WebAssembly
    • Compilation
    • AssemblyScript
  • Analysis
    • When not to use
    • When to use
    • Summary of Caveats
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.