JavaScript Concurrency
eBook - ePub

JavaScript Concurrency

Adam Boduch

Share book
  1. 292 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

JavaScript Concurrency

Adam Boduch

Book details
Book preview
Table of contents
Citations

About This Book

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is JavaScript Concurrency an online PDF/ePUB?
Yes, you can access JavaScript Concurrency by Adam Boduch in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in JavaScript. We have over one million books available in our catalogue for you to explore.

Information

Year
2015
ISBN
9781785889233
Edition
1

JavaScript Concurrency


Table of Contents

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

JavaScript Concurrency

Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2015
Production reference: 1181215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-923-3
www.packtpub.com

Credits

Author
Adam Boduch
Reviewer
August Marcello III
Commissioning Editor
Edward Gordon
Acquisition Editor
Ruchita Bhansali
Content Development Editor
Divij Kotian
Technical Editor
Gebin George
Copy Editor
Yesha Gangani
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Graphics
Jason Monteiro
Production Coordinator
Melwyn Dsa
Cover Work
Melwyn Dsa

About the Author

Adam Boduch has been involved with large-scale JavaScript development for nearly 10 years. Before moving to the front-end, he worked on several large-scale cloud computing products, using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems, and the scaling challenges they pose. He is the author of several JavaScript books, including JavaScript at Scale, Packt Publishing, and is passionate about innovative user experiences and high performance.

About the Reviewer

August Marcello III is a highly passionate software engineer with nearly two decades of experience in the design, implementation, and deployment of modern client-side web application architectures in enterprise. An exclusive focus on delivering compelling SaaS-based User Experiences throughout the Web ecosystem has proven to be rewarding both personally and professionally. His passion for emerging technologies in general, combined with a particular focus on forward-thinking JavaScript platforms, have been a primary driver in his pursuit of technical excellence. When he's not coding, he can be found trail running, mountain biking, and spending time with his family and friends.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
Support files, eBooks, discount offers, and more
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and readPackt's entire library of books.

Why subscribe?

  • Fully searchable across every book published by Packt
  • Copy and paste, print, and bookmark content
  • On demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
For Melissa, Jason, and Simon, thanks for all your love and support.
2323__perlego__ch...

Table of contents