You are previewing JavaScript Concurrency.
O'Reilly logo
JavaScript Concurrency

Book Description

Build better software with concurrent JavaScript programming, and unlock a more efficient and forward thinking approach to web development

About This Book

  • Apply the core principles of concurrency to both browser and server side development

  • Explore the latest tools and techniques at the forefront of concurrent programming, including JavaScript promises, web workers, and generators

  • Learn how concurrent and parallel programming can help you tackle the challenges of fast, data heavy web development

  • Who This Book Is For

    JavaScript Concurrency is written for any JavaScript developer who wants to learn how to write more efficient, powerful, and maintainable applications that utilize the latest developments in the JavaScript language.

    All aspects of concurrent, asynchronous, and parallel programming are covered from first principles and by the end of the book you’ll be able to create a fully-worked application that leverages all the topics covered in the book.

    What You Will Learn

  • Understand exactly how JavaScript works in a web browser environment, and how these mechanisms power our event-driven JavaScript code

  • Use promises to turn complex synchronization scenarios into readable and maintainable values

  • Compute values lazily and avoid unnecessary memory allocations using generators.

  • Write concurrent code that doesn’t feel like concurrent code by abstracting away boilerplate chores

  • Leverage true hardware parallelism with web workers to get a better performance

  • Get to grips with the NodeJS model of concurrency and learn why it’s good for I/O-intensive web applications

  • In Detail

    Concurrent programming may sound abstract and complex, but it helps to deliver a better user experience. With single threaded JavaScript, applications lack dynamism. This means that when JavaScript code is running, nothing else can happen. The DOM can’t update, which means the UI freezes. In a world where users expect speed and responsiveness – in all senses of the word – this is something no developer can afford.

    Fortunately, JavaScript has evolved to adopt concurrent capabilities – one of the reasons why it is still at the forefront of modern web development. This book helps you dive into concurrent JavaScript, and demonstrates how to apply its core principles and key techniques and tools to a range of complex development challenges. Built around the three core principles of concurrency – parallelism, synchronization, and conservation – you’ll learn everything you need to unlock a more efficient and dynamic JavaScript, to lay the foundations of even better user experiences.

    Throughout the book you’ll learn how to put these principles into action by using a range of development approaches. Covering everything from JavaScript promises, web workers, generators and functional programming techniques, everything you learn will have a real impact on the performance of your applications. You’ll also learn how to move between client and server, for a more frictionless and fully realized approach to development. With further guidance on concurrent programming with Node.js, JavaScript Concurrency is committed to making you a better web developer.

    The best developers know that great design is about more than the UI – with concurrency, you can be confident every your project will be expertly designed to guarantee its dynamism and power.

    Style and approach

    Beginning with the fundamentals of concurrency and how they apply to JavaScript development, the book then takes you through the relevant constructs that will help you implement concurrent code. You’ll learn how even the most abstract and theoretical aspects of concurrent programming help you solve real world challenges, with clear and practical demonstrations that show you how concurrent JavaScript will make you a better developer.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

    Table of Contents

    1. JavaScript Concurrency
      1. Table of Contents
      2. JavaScript Concurrency
      3. Credits
      4. About the Author
      5. About the Reviewer
      6. www.PacktPub.com
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
      7. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      8. 1. Why JavaScript Concurrency?
        1. Synchronous JavaScript
          1. Synchronicity is easy to understand
          2. Asynchronous is inevitable
            1. Asynchronous browsers
        2. Types of concurrency
          1. Asynchronous actions
          2. Parallel actions
        3. JavaScript concurrency principles: Parallelize, Synchronize, Conserve
          1. Parallelize
          2. Synchronize
            1. The Promise API
          3. Conserve
        4. Summary
      9. 2. The JavaScript Execution Model
        1. Everything is a task
          1. Meet the players
          2. The Execution environment
          3. Event loops
          4. Task queues
        2. Execution contexts
          1. Maintaining execution state
          2. Job queues
        3. Creating tasks using timers
          1. Using setTimeout()
          2. Using setInterval()
        4. Responding to DOM events
          1. Event targets
          2. Managing event frequency
        5. Responding to network events
          1. Making requests
          2. Coordinating requests
        6. Concurrency challenges with this model
          1. Limited opportunity for parallelism
          2. Synchronization through callbacks
        7. Summary
      10. 3. Synchronizing with Promises
        1. Promise terminology
          1. Promise
          2. State
          3. Executor
          4. Resolver
          5. Rejector
          6. Thenable
        2. Resolving and rejecting promises
          1. Resolving promises
          2. Rejecting promises
          3. Empty promises
        3. Reacting to promises
          1. Resolution job queues
          2. Using promised data
          3. Error callbacks
          4. Always reacting
          5. Resolving other promises
          6. Promise–like objects
        4. Building callback chains
          1. Promises only change state once
          2. Immutable promises
          3. Many then callbacks, many promises
          4. Passing promises around
        5. Synchronizing several promises
          1. Waiting on promises
          2. Cancelling promises
        6. Promises without executors
        7. Summary
      11. 4. Lazy Evaluation with Generators
        1. Call stacks and memory allocation
          1. Bookmarking function contexts
          2. Sequences instead of arrays
        2. Creating generators and yielding values
          1. Generator function syntax
          2. Yielding values
          3. Iterating over generators
        3. Infinite sequences
          1. No end in sight
          2. Alternating sequences
        4. Deferring to other generators
          1. Selecting a strategy
          2. Interweaving generators
        5. Passing data to generators
          1. Reusing generators
          2. Lightweight map/reduce
        6. Coroutines
          1. Creating coroutine functions
          2. Handling DOM events
          3. Handling promised values
        7. Summary
      12. 5. Working with Workers
        1. What are workers?
          1. OS threads
          2. Event targets
          3. True parallelism
        2. Types of workers
          1. Dedicated workers
          2. Sub-workers
          3. Shared workers
        3. Worker environments
          1. What's available, what isn't?
          2. Loading scripts
        4. Communicating with workers
          1. Posting messages
          2. Message serialization
          3. Receiving messages from workers
        5. Sharing application state
          1. Sharing memory
          2. Fetching resources
          3. Communicating between pages
        6. Performing sub-tasks with sub-workers
          1. Dividing work into tasks
          2. A word of caution
        7. Error handling in web workers
          1. Error condition checking
          2. Exception handling
        8. Summary
      13. 6. Practical Parallelism
        1. Functional programming
          1. Data in, data out
          2. Immutability
          3. Referential transparency and time
        2. Do we need to go parallel?
          1. How big is the data?
          2. Hardware concurrency capabilities
          3. Creating tasks and assigning work
        3. Candidate problems
          1. Embarrassingly parallel
          2. Searching collections
          3. Mapping and reducing
        4. Keeping the DOM responsive
          1. Bottom halves
          2. Translating DOM manipulation
          3. Translating DOM events
        5. Summary
      14. 7. Abstracting Concurrency
        1. Writing concurrent code
          1. Hiding the concurrency mechanism
          2. Without concurrency
        2. Worker communication with promises
          1. Helper functions
          2. Extending postMessage()
          3. Synchronizing worker results
        3. Lazy workers
          1. Reducing overhead
          2. Generating values in workers
          3. Lazy worker chains
        4. Using Parallel.js
          1. How it works
          2. Spawning workers
          3. Mapping and reducing
        5. Worker pools
          1. Allocating pools
          2. Scheduling jobs
        6. Summary
      15. 8. Evented IO with NodeJS
        1. Single threaded IO
          1. IO is slow
          2. IO events
          3. Multi-threading challenges
        2. More connections, more problems
          1. Deploying to the Internet
          2. The C10K problem
          3. Lightweight event handlers
        3. Evented network IO
          1. Handling HTTP requests
          2. Streaming responses
          3. Proxy network requests
        4. Evented file IO
          1. Reading from files
          2. Writing to files
          3. Streaming reads and writes
        5. Summary
      16. 9. Advanced NodeJS Concurrency
        1. Coroutines with Co
          1. Generating promises
          2. Awaiting values
          3. Resolving values
          4. Asynchronous dependencies
          5. Wrapping coroutines
        2. Child Processes
          1. Blocking the event loop
          2. Forking processes
          3. Spawning external processes
          4. Inter-process communication
        3. Process Clusters
          1. Challenges with process management
          2. Abstracting process pools
        4. Server clusters
          1. Proxying requests
          2. Facilitating micro-services
          3. Informed load balancing
        5. Summary
      17. 10. Building a Concurrent Application
        1. Getting started
          1. Concurrency first
          2. Retrofitting concurrency
          3. Application types
        2. Requirements
          1. The overall goal
          2. The API
          3. The UI
        3. Building the API
          1. The HTTP server and routing
          2. Co-routines as handlers
          3. The create chat handler
          4. The join chat handler
          5. The load chat handler
          6. The send message handler.
          7. Static handlers
        4. Building the UI
          1. Talking to the API
          2. Implementing the HTML
          3. DOM events and manipulation
          4. Adding an API worker
        5. Additions and improvements
          1. Clustering the API
          2. Cleaning up chats
          3. Asynchronous entry points
          4. Who's typing?
          5. Leaving chats
          6. Polling timeouts
        6. Summary
      18. Index