SlideShare une entreprise Scribd logo
1  sur  60
There’s no sleep()
    in Javascript

Introduction to node.js
      twitter.com/jacek_becela
           github.com/ncr
node.js
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
• API for highly concurrent programming
 • All I/O is non-blocking (asynchronous)
 • Achieved using Event Loop
Two approaches to I/O
// blocking I/O + threads
var urls = db.query("select * from urls"); // wait
urls.each(function (url) {
  var page = http.get(url); // wait
  save(page); // wait
});
 
// non-blocking I/O + event loop
db.query("select * from urls", function (urls) {
  urls.each(function (url) {
    http.get(url, function (page) {
      save(page);
    });
  });
});
I/O Costs




http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles




         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles



         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles


        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles

        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles
• NETWORK: 240,000,000 cycles
       http://nodejs.org/jsconf.pdf
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Why threads are bad
Why threads are bad
• Hard to program
Why threads are bad
• Hard to program
• Shared state and locks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
• Context switching costs
When threads are good
When threads are good

• Support Multi-core CPUs
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
• Threads count == CPU cores count
Event Loop
 user perspective
• You already use it everyday for I/O
• You register callbacks for events
• Your callback is eventually fired
      $("a").click(function () {
        console.log("clicked!");
      });
       
      $.ajax(..., function (...) {
        console.log("internets!");
      });
Event Loop
 life cycle
Event Loop
            life cycle
• Initialize empty event loop (just an array)
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
• All this happens in a single thread
Event Loop
 life cycle
Event Loop
             life cycle
• Iterate over a list of events and callbacks
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
• Program exits when Event Loop is empty
Event Loop limitations
Event Loop limitations
• Callbacks have to return fast
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
 • Communication using message passing
Hello World
var sys = require('sys'),
   http = require('http');
http.createServer(function (req, res) {
  setTimeout(function () {
    res.sendHeader(200, {'Content-Type': 'text/plain'});
    res.write('Hello World');
    res.close();
  }, 2000);
}).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
sleep()
sleep()
• It is a blocking call per definition
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
• The real reason: JavaScript exceution and
  Event Loop live in a single thread
Where to go next
• github.com/ry/node
• groups.google.com/group/nodejs
• howtonode.org
• dailyjs.org
• search twitter for node.js
• github.com/ncr/flickr_spy
Demo

Contenu connexe

Tendances

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
A Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on AndroidA Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on AndroidOutware Mobile
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...Edureka!
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da HoodMichel Schudel
 

Tendances (20)

JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
A Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on AndroidA Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on Android
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Express js
Express jsExpress js
Express js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
NestJS
NestJSNestJS
NestJS
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da Hood
 

Similaire à Introduction to node.js

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
 
"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
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS DebuggingRami Sayar
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
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
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012mumrah
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentationasync_io
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleJulian Gamble
 
Kernelci.org needs you!
Kernelci.org needs you!Kernelci.org needs you!
Kernelci.org needs you!Mark Brown
 

Similaire à Introduction to node.js (20)

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
 
"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)
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
SDN TEST Suite
SDN TEST SuiteSDN TEST Suite
SDN TEST Suite
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS Debugging
 
What is Node.js
What is Node.jsWhat is Node.js
What is Node.js
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
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?
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
 
Node.js
Node.jsNode.js
Node.js
 
Kernelci.org needs you!
Kernelci.org needs you!Kernelci.org needs you!
Kernelci.org needs you!
 

Dernier

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Introduction to node.js

  • 1. There’s no sleep() in Javascript Introduction to node.js twitter.com/jacek_becela github.com/ncr
  • 3. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules
  • 4. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules • API for highly concurrent programming • All I/O is non-blocking (asynchronous) • Achieved using Event Loop
  • 5. Two approaches to I/O // blocking I/O + threads var urls = db.query("select * from urls"); // wait urls.each(function (url) {   var page = http.get(url); // wait   save(page); // wait });   // non-blocking I/O + event loop db.query("select * from urls", function (urls) {   urls.each(function (url) {     http.get(url, function (page) {       save(page);     });   }); });
  • 7. I/O Costs • L1: 3 cycles http://nodejs.org/jsconf.pdf
  • 8. I/O Costs • L1: 3 cycles • L2: 14 cycles http://nodejs.org/jsconf.pdf
  • 9. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles http://nodejs.org/jsconf.pdf
  • 10. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles http://nodejs.org/jsconf.pdf
  • 11. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles • NETWORK: 240,000,000 cycles http://nodejs.org/jsconf.pdf
  • 15. Why threads are bad • Hard to program
  • 16. Why threads are bad • Hard to program • Shared state and locks
  • 17. Why threads are bad • Hard to program • Shared state and locks • Deadlocks
  • 18. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency
  • 19. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity
  • 20. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions
  • 21. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions • Context switching costs
  • 23. When threads are good • Support Multi-core CPUs
  • 24. When threads are good • Support Multi-core CPUs • CPU-heavy work
  • 25. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state
  • 26. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state • Threads count == CPU cores count
  • 27. Event Loop user perspective • You already use it everyday for I/O • You register callbacks for events • Your callback is eventually fired $("a").click(function () {   console.log("clicked!"); });   $.ajax(..., function (...) {   console.log("internets!"); });
  • 29. Event Loop life cycle • Initialize empty event loop (just an array)
  • 30. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code
  • 31. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code
  • 32. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop
  • 33. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached
  • 34. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating
  • 35. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating • All this happens in a single thread
  • 37. Event Loop life cycle • Iterate over a list of events and callbacks
  • 38. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select
  • 39. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep
  • 40. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop
  • 41. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback
  • 42. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback • Program exits when Event Loop is empty
  • 44. Event Loop limitations • Callbacks have to return fast
  • 45. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff
  • 46. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs
  • 47. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes
  • 48. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff
  • 49. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks
  • 50. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks • Communication using message passing
  • 51. Hello World var sys = require('sys'),    http = require('http'); http.createServer(function (req, res) {   setTimeout(function () {     res.sendHeader(200, {'Content-Type': 'text/plain'});     res.write('Hello World');     res.close();   }, 2000); }).listen(8000); sys.puts('Server running at http://127.0.0.1:8000/');
  • 53. sleep() • It is a blocking call per definition
  • 54. sleep() • It is a blocking call per definition • Browser JS has no blocking functions
  • 55. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event
  • 56. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point...
  • 57. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point... • The real reason: JavaScript exceution and Event Loop live in a single thread
  • 58. Where to go next • github.com/ry/node • groups.google.com/group/nodejs • howtonode.org • dailyjs.org • search twitter for node.js • github.com/ncr/flickr_spy
  • 59.
  • 60. Demo

Notes de l'éditeur