Concurrency

with

JavaScript

Downtown ReactJS Meetup - 2018/10/30

Part 2

Part 2

  • Quick Recap
  • Fiber
  • Async Rendering
  • Web Workers
    • examples

Currency vs Parallelism

  • Asynchronous vs Synchronous
  • Blocking vs Non-Blocking
  • Single Process vs Cooperative Multitasking
  • Preemptive vs Non-Preemptive
  • Simultaneous Multi Threading (SMT - hyper threading)

OS vs Userland

What is Concurrency?

two or more tasks can start, run, and complete in overlapping time periods. It doesn't rule out that the tasks can be both be running at the same instant. For example, multitasking on a single- vs multi-core machine.

... a property of a program or system

What is Parallelism?

tasks literally run at the same time e.g., on a multicore processor.

parallelism as the run-time behaviour of executing multiple tasks at the same time

Multi-

Multi-tasking

    -is a Process

    -top-level execution container

    -have their own memory space

    -communicate with other processes via IPC

    -sandbox / safety

 

Multi-threading

    -runs inside a process

    -share same memory

    -need to manage sync

OS vs Userland

JavaScript is

Single Threaded

Race conditions cannot happen

"Everything runs in parallel except your code"

JavaScript is

Synchronous

one operation is executed at a time

write code to make it behave asynchronous

JavaScript's Concurrency model is based on the

Event Loop

The goal is to move away from this

Multi-Theaded - Async

DOM

  • find node(s) of interest
    • page loaded? element available?
  • update node(s) if necessary
    • when to update? data incoming?
  • repeat

OS vs Userland

DOM

DOM is tree-structured

DOM trees are easy to traverse

ENTER THE SPA

need to manipulate the tree A LOT!!

Virtual DOM*

  • simplified copy of the DOM (JS objects)
  • browser-independent
  • can be optimized - diffing, batch updates

*Facebook did not invent this

React Fiber

Background

  • components describe what to render
    • react controls when to render
  • gives react opportunity to optimize rendering
    • pause, delay, abort
  • walks the tree recursively and calls render functions of the whole updated tree during a single tick.

Control over Scheduling

React Fiber

  • It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal.
  • This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.

OS vs Userland

Control over Scheduling

React Fiber

key features: the ability to pause, abort, or reuse work as new updates come in; the ability to assign priority to different types of updates; and new concurrency primitives.

incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

React Fiber

Reconciliation

  • when you render a React application, a tree of nodes that describes the app is generated and saved in memory. This tree is then flushed to the rendering environment
  • When the app is updated, a new tree is generated. The new tree is diffed with the previous tree to compute which operations are needed to update the rendered app.

React Fiber

  • Scheduling
    • the process of determining when work should be performed
  • Work
    • computations that must be performed. Work is usually the result of an update (e.g. setState).

React Fiber

  • The reconciler does the work of computing which parts of a tree have changed
  • The renderer then uses that information to actually update the rendered app.

Reconciliation is not Rendering

React Fiber

  • In a UI, it's not necessary for every update to be applied immediately; in fact, doing so can be wasteful, causing frames to drop and degrading the user experience.
  • Different types of updates have different priorities — an animation update needs to complete more quickly than, say, an update from a data store.
  • A push-based approach requires the app (you, the programmer) to decide how to schedule work. A pull-based approach allows the framework (React) to be smart and make those decisions for you.

Take aways

https://github.com/acdlite/react-fiber-architecture

Rendering

CPU

  • Creating Nodes
  • Re-rendering

IO

  • data fetching
  • code splitting
  • low CPU, remain responsive
  • high CPU, appears synchronous
  • low IO, control loading state
  • high IO, render tree when ready

ASYNC Rendering

Time Slicing

  • React does not block the thread while rendering
  • Only the final rendered state is displayed

Suspense

  • Pause any state update until the data is ready
  • Add async data to any component without 'plumbing'
  • high CPU, appears synchronous
  • low CPU, remain responsive
  • high IO, render tree when ready
  • low IO, control loading state

Web Workers

  • Dedicated Worker
  • Shared Worker

isolated thread

    -code lives in its own file

    -some APIs are not accessible (i.e. DOM)

postMessage

    -communicates with the Main Thread

Spawn other workers (sub-workers)

https://github.com/ampproject/worker-dom

Web Workers

  • Dedicated Worker
  • Shared Worker

isolated thread

    -code lives in its own file

    -some APIs are not accessible (i.e. DOM)

postMessage

    -communicates with the Main Thread

Spawn other workers (sub-workers)

main

worker

Uploading a CSV file

with Web Workers

Web Workers makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

Uploading a CSV file

  • user is uploading a csv file
  • csv file is parsed
  • csv file is validated

Criteria

  • Errors
    • misspelled header
    • unknown header
    • missing required header
    •  

Flow

  • parse csv file
  • validate headers
  • validate items

Resources:

  • https://github.com/acdlite/react-fiber-architecture
  • https://blog.usejournal.com/notes-from-dan-abramovs-beyond-react-16-talk-5861a92dcdce
  • https://reactjs.org/docs/design-principles.html
  • https://blog.pusher.com/time-slice-suspense-api-react-17/
  • https://github.com/ampproject/worker-dom
Made with Slides.com