SlideShare uma empresa Scribd logo
1 de 14
JavaScript Event Loop
Not yo mama’s multithreaded approach.
slidesha.re/ZPC2nD
Who is Thomas Hunter?
• Web developer for 8+ years
• Dow, Ford, Quicken, Startup, Barracuda
• Started development with PHP & MySQL
• Became a Node.js fanboy
• Writing a book on Backbone.js for Packt
• @tlhunter | me@thomashunter.name
What does MultiThreaded mean?
• Makes use of separate CPU Cores as “Threads”
• Uses a single process within the Operating System
• True concurrency
• Can have Race Conditions (simultaneous memory use)
• “Hard” to get it right
• Ran out of Ghz, hardware adds more cores
JavaScript is SingleThreaded
• Makes use of a single CPU core
• CPU intensive work is never “concurrent”
• Easier to pull off, as in less technical difficulties
Technical Implementation
• Stack:
• Functions to run and available variables
• More added as code is run
• Stuff guaranteed to run in order
• Heap:
• “Chaotic” listing of objects
• Queue:
• Gets added to stack when stack empty
• setTimeout and setInterval added here
Credit: Mozilla Developer Network
http://mzl.la/Y5Dh2x
Example Code-run
console.log("Adding code to the queue");
setTimeout(function() { // Added somewhere in Heap
console.log("Running next code from queue");
}, 0);
function a(x) { // Added somewhere in Heap
console.log("a() frame added to stack");
b(x);
console.log("a() frame removed from stack");
}
function b(y) { // Added somewhere in Heap
console.log("b() frame added to stack");
console.log("Value passed in is " + y);
console.log("b() frame removed from stack");
}
console.log("Starting work for this stack");
a(42);
console.log("Ending work for this stack");
Adding code to the queue
Starting work for this stacka() frame added to stackb()frame added to stackValue passed in is 42b() frameremoved from stacka() frame removed fromstackEnding work for this stackRunning next codefrom queue
Your App is Mostly Asleep
• Node.js:All I/O is non-blocking
• E.g. it gets thrown into the Queue
• Browser:Wait for a click to happen
• PHP:Wait for a MySQL query to run
• These show how slow I/O can be →
L1-Cache 3 cyclesL2-Cache
14 cyclesRAM 250
cyclesDisk 41,000,000
Network 240,000,000
Sequential vs Parallel
• Traditional web apps perform each I/O Sequentially
• With an Event Loop, they can be run in Parallel
• Since most time is wasted doing I/O, very inefficient
Non JS Event Loops
• Event Loops can be implemented in other languages
• However, JavaScript was built this way, feels “natural”
• Examples:
• Ruby: EventMachine
• Python:Twisted & Tornado
• PHP: ReactPHP
!JS Event Loop Examples
require 'eventmachine'
module Echo
def post_init
puts "Someone Connected"
end
def receive_data data
send_data "#{data}"
close_connection if data =~ /quit/if
end
end
EventMachine.run {
EventMachine.start_server "127.0.0.1", 8081, Echo
}
var net = require('net');
var server = net.createServer(function (socket) {
console.log('Someone Connected');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
EventMachine in Ruby Node.js
Event Loops are Awesome!
• No race conditions
• Typical web apps spend their time waiting on I/O
• No funky syntax; it just works
• Perform I/O operations “in parallel” easily
• Stateful web applications are easy compared to PHP
• Long run apps, don’t need web servers, shared data...
Event Loops aren’t Awesome!
• CPU intensive work will block your process
• You can offload work to different processes (Node.js)
• It isn’t making use of those 8 cores you’ve got
• You can use the Multi-node module though (Node.js)
• Memory leaks are possible, not so with PHP
• You can program better and prevent it though ;-)
Web Workers
• You can use MultiThreaded JavaScript in your browser
• IE10, Firefox 3.5, Chrome 4, Safari 4, Opera 10.6
• var worker = new Worker('task.js');
• Use Message Passing to share data
• You share simple JSON data, not complex objects
• Prevents deadlocks/race conditions because of this
Conclusion
• Great for I/O bound applications (most web apps)
• Horrible for CPU bound applications (do it in C ;)
• Appears to be a single multi-threaded process
• “Fakes” concurrency
• thomashunter.name @tlhunter slidesha.re/ZPC2nD

Mais conteúdo relacionado

Mais procurados

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An IntroductionSam Brannen
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingHaim Michael
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 

Mais procurados (20)

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 

Destaque

Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event LoopTorontoNodeJS
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objectsMuhammad Ahmed
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpretedMartha Schumann
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 

Destaque (9)

Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event Loop
 
Event loop
Event loopEvent loop
Event loop
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objects
 
Array
ArrayArray
Array
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 

Semelhante a JavaScript Event Loop

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Scalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJSScalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJSAndhy Koesnandar
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami SayarFITC
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Felix Geisendörfer
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrencypgriess
 
Firefox Crash Reporting (@ Open Source Bridge)
Firefox Crash Reporting (@ Open Source Bridge)Firefox Crash Reporting (@ Open Source Bridge)
Firefox Crash Reporting (@ Open Source Bridge)lauraxthomson
 
Crash reports pycodeconf
Crash reports pycodeconfCrash reports pycodeconf
Crash reports pycodeconflauraxthomson
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.jsNitin Gupta
 

Semelhante a JavaScript Event Loop (20)

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Scalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJSScalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJS
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Node azure
Node azureNode azure
Node azure
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrency
 
Node and Azure
Node and AzureNode and Azure
Node and Azure
 
Firefox Crash Reporting (@ Open Source Bridge)
Firefox Crash Reporting (@ Open Source Bridge)Firefox Crash Reporting (@ Open Source Bridge)
Firefox Crash Reporting (@ Open Source Bridge)
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Crash reports pycodeconf
Crash reports pycodeconfCrash reports pycodeconf
Crash reports pycodeconf
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.js
 

Último

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

JavaScript Event Loop

  • 1. JavaScript Event Loop Not yo mama’s multithreaded approach. slidesha.re/ZPC2nD
  • 2. Who is Thomas Hunter? • Web developer for 8+ years • Dow, Ford, Quicken, Startup, Barracuda • Started development with PHP & MySQL • Became a Node.js fanboy • Writing a book on Backbone.js for Packt • @tlhunter | me@thomashunter.name
  • 3. What does MultiThreaded mean? • Makes use of separate CPU Cores as “Threads” • Uses a single process within the Operating System • True concurrency • Can have Race Conditions (simultaneous memory use) • “Hard” to get it right • Ran out of Ghz, hardware adds more cores
  • 4. JavaScript is SingleThreaded • Makes use of a single CPU core • CPU intensive work is never “concurrent” • Easier to pull off, as in less technical difficulties
  • 5. Technical Implementation • Stack: • Functions to run and available variables • More added as code is run • Stuff guaranteed to run in order • Heap: • “Chaotic” listing of objects • Queue: • Gets added to stack when stack empty • setTimeout and setInterval added here Credit: Mozilla Developer Network http://mzl.la/Y5Dh2x
  • 6. Example Code-run console.log("Adding code to the queue"); setTimeout(function() { // Added somewhere in Heap console.log("Running next code from queue"); }, 0); function a(x) { // Added somewhere in Heap console.log("a() frame added to stack"); b(x); console.log("a() frame removed from stack"); } function b(y) { // Added somewhere in Heap console.log("b() frame added to stack"); console.log("Value passed in is " + y); console.log("b() frame removed from stack"); } console.log("Starting work for this stack"); a(42); console.log("Ending work for this stack"); Adding code to the queue Starting work for this stacka() frame added to stackb()frame added to stackValue passed in is 42b() frameremoved from stacka() frame removed fromstackEnding work for this stackRunning next codefrom queue
  • 7. Your App is Mostly Asleep • Node.js:All I/O is non-blocking • E.g. it gets thrown into the Queue • Browser:Wait for a click to happen • PHP:Wait for a MySQL query to run • These show how slow I/O can be → L1-Cache 3 cyclesL2-Cache 14 cyclesRAM 250 cyclesDisk 41,000,000 Network 240,000,000
  • 8. Sequential vs Parallel • Traditional web apps perform each I/O Sequentially • With an Event Loop, they can be run in Parallel • Since most time is wasted doing I/O, very inefficient
  • 9. Non JS Event Loops • Event Loops can be implemented in other languages • However, JavaScript was built this way, feels “natural” • Examples: • Ruby: EventMachine • Python:Twisted & Tornado • PHP: ReactPHP
  • 10. !JS Event Loop Examples require 'eventmachine' module Echo def post_init puts "Someone Connected" end def receive_data data send_data "#{data}" close_connection if data =~ /quit/if end end EventMachine.run { EventMachine.start_server "127.0.0.1", 8081, Echo } var net = require('net'); var server = net.createServer(function (socket) { console.log('Someone Connected'); socket.pipe(socket); }); server.listen(1337, '127.0.0.1'); EventMachine in Ruby Node.js
  • 11. Event Loops are Awesome! • No race conditions • Typical web apps spend their time waiting on I/O • No funky syntax; it just works • Perform I/O operations “in parallel” easily • Stateful web applications are easy compared to PHP • Long run apps, don’t need web servers, shared data...
  • 12. Event Loops aren’t Awesome! • CPU intensive work will block your process • You can offload work to different processes (Node.js) • It isn’t making use of those 8 cores you’ve got • You can use the Multi-node module though (Node.js) • Memory leaks are possible, not so with PHP • You can program better and prevent it though ;-)
  • 13. Web Workers • You can use MultiThreaded JavaScript in your browser • IE10, Firefox 3.5, Chrome 4, Safari 4, Opera 10.6 • var worker = new Worker('task.js'); • Use Message Passing to share data • You share simple JSON data, not complex objects • Prevents deadlocks/race conditions because of this
  • 14. Conclusion • Great for I/O bound applications (most web apps) • Horrible for CPU bound applications (do it in C ;) • Appears to be a single multi-threaded process • “Fakes” concurrency • thomashunter.name @tlhunter slidesha.re/ZPC2nD

Notas do Editor

  1. Old school colloquialism, ya dig it?
  2. Why I’m credible (OR AM I?!)
  3. Explain multithreaded, how it is the true way to to do concurrent programming, and the best way to make use of systems with multiple cores (which is pretty much every system these days), but also allude to the difficulty of doing so.
  4. Describe how it is definitely not multithreaded, has downfalls of not making use of multiple CPUs, but kinda appears to be concurrent, and that it is easier to implement technologically.
  5. If you run the code: function a(x) { b(x+1); } function b(y) { alert(y); } a(12); Those all get added as “frames” within the current stack. Once you do something with a callback that gets executed after I/O happens, or a DOM event, that code is actually added to the Queue. When the current stack is complete it grabs the next item in the queue (if it’s ready). The heap doesn’t really matter, it’s just where the browser throws stuff in RAM.
  6. Run the code on the left (either in Node or your browser) and you’ll see the code on the right. The setTimeout automatically adds the execution to the next queue. The a() b() function calls are added to the stack since they’re running right now. Notice how the order isn’t exactly what you would expect. The setTimeout(), if this were a MultiThreaded application, would likely run immediately some of the times and maybe half way through execution other times.
  7. I mention PHP/MySQL a lot since I used it for several years, but the same applies to most single core languages. Basically, your app is almost always waiting on other shit to happen, unless you’re crunching a ton of numbers. Web apps are all I/O bound! Grab this remote RSS feed, talk to a database, send an email, you name it. The math parts and concatenating strings are super fast. The graph on the right shows just how intense this is.
  8. I adapted this diagram from a CodeSchool tutorial, it does a great job showing how stuff executes seemingly in parallel. Since I/O isn’t CPU bound, it can be done at the same time. The Sequential I/O section represents a PHP or Ruby or any other traditionally built application. The Parallel I/O section represents an application that is either MultiThreaded or using an EventLoop with non blocking I/O.
  9. You can implement event loops in other languages, but it won’t be pretty since you’ll need to use some specific syntax for registering callbacks. JS is cool though because this is built in, it’s just how it works, it feels au naturale. Maybe mention Node.js using LibUV, which relies on lower level utilities to tell it when to “wake” up.
  10. Here’s an Apples to Oranges comparison of EventLoops. Both of these examples were taken from their respective homepages (slightly tweaked for verbiage). I don’t know Ruby at all, and I honestly don’t know if these do the same things. This is just meant to show that most languages can implement an EventLoop, even when it’s not built in. The Ruby code is a little more terse, since it’s not “native”. You also have to be careful when building scripts this way, as the libraries you use should have non-blocking I/O.
  11. A race condition is when two bits of code running on different CPUs write to the same memory at the same moment. Who wins? If X = 10; thread 1 tries to add 2 to it, and thread 2 tries to add 3 to it, simultaneously, the value will become 12 or 13, not 15. Stateful apps in PHP requires the use of Memcache or a database. Node.js can simply use local variables. Parallel cURL requests can be done with a complex library, but in Node.js one can simply use callbacks.
  12. Mention the cons of single threaded event loops (as well as ways to fix it since I’m biased). Multi-node can spin up several processes for handling HTTP traffic, you prolly want to set it to the number of CPUs you have. Memory leaks can happen since your app is always running. PHP runs for a moment and then dies, Node.js can run for weeks. Perhaps mention ways to mitigate issues.
  13. Browser support looks pretty good, feel free to use it today. Node.js doesn’t have the Worker() object available, but there are plenty of alternatives.
  14. Not sure if this slide should stay, it duplicates information from one and two slides previous.