All you need to know about the JavaScript event loopSaša Tatar
Learn the difference between JavaScript Engine, JavaScript Runtime, what is JavaScript event loop and why we should care.
At the end the presentation goes through a couple of examples and implementations of throttle and debounce utility functions.
Introduction to Flutter sharing session organized by MaGIC Cyberjaya.
In this session I focus on introducing important widgets to build simple application. The widgets are group as:
- Boilerplate (scaffold) widget
- Layouting widgets
- Design widgets.
Hopefully this will help those who would like to start and discover mobile app development with Flutter.
Full version of the presentation can be found on following link:
https://www.facebook.com/mymagic.my/videos/1141346269560536/
All you need to know about the JavaScript event loopSaša Tatar
Learn the difference between JavaScript Engine, JavaScript Runtime, what is JavaScript event loop and why we should care.
At the end the presentation goes through a couple of examples and implementations of throttle and debounce utility functions.
Introduction to Flutter sharing session organized by MaGIC Cyberjaya.
In this session I focus on introducing important widgets to build simple application. The widgets are group as:
- Boilerplate (scaffold) widget
- Layouting widgets
- Design widgets.
Hopefully this will help those who would like to start and discover mobile app development with Flutter.
Full version of the presentation can be found on following link:
https://www.facebook.com/mymagic.my/videos/1141346269560536/
Java DataBase Connectivity API (JDBC API)Luzan Baral
JDBC is a Java-based data access technology (Java Standard Edition platform) from Oracle Corporation. This technology is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
This is an interactive PowerPoint presentation I made for my seminar at my workplace. It talks and illustrates how the JavaScript engine works when executing code. It also contains a step-by-step animation which demonstrates the usage of the JavaScript event loop.
Feel free to use and refer content. Copyrights reserved.
This slide from Android Application Programming Seminar at a Technical University of Vietnam.
Throughout the slide, audience will have the general knowledge about Android OS, Architecture. The slide also provide the Android Application structure, the choices of framework or language to develop an Android application.
Real Time Audio is an application is written for this seminar.
Everyone can download from Google Play:
https://play.google.com/store/apps/details?id=junoteam.com.realtimerecording
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Java DataBase Connectivity API (JDBC API)Luzan Baral
JDBC is a Java-based data access technology (Java Standard Edition platform) from Oracle Corporation. This technology is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
This is an interactive PowerPoint presentation I made for my seminar at my workplace. It talks and illustrates how the JavaScript engine works when executing code. It also contains a step-by-step animation which demonstrates the usage of the JavaScript event loop.
Feel free to use and refer content. Copyrights reserved.
This slide from Android Application Programming Seminar at a Technical University of Vietnam.
Throughout the slide, audience will have the general knowledge about Android OS, Architecture. The slide also provide the Android Application structure, the choices of framework or language to develop an Android application.
Real Time Audio is an application is written for this seminar.
Everyone can download from Google Play:
https://play.google.com/store/apps/details?id=junoteam.com.realtimerecording
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Node has captured the attention of early adopters by clearly differentiating itself as being asynchronous from the ground up while remaining accessible. Now that server side JavaScript is at the cutting edge of the asynchronous, real time web, it is in a much better position to establish itself as the go to language for also making synchronous, CRUD webapps and gain a stronger foothold on the server.
This talk covers the current state of server side JavaScript beyond Node. It introduces Common Node, a synchronous CommonJS compatibility layer using node-fibers which bridges the gap between the different platforms. We look into Common Node's internals, compare its performance to that of other implementations such as RingoJS and go through some ideal use cases.
Mathilde Lemée & Romain Maton
La théorie, c’est bien, la pratique … aussi !
Venez nous rejoindre pour découvrir les profondeurs de Node.js !
Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui !
http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html
Building complex async applications is really hard. Whether you use callbacks, Promises, or EventEmitters, Error objects should have a place in your utility belt. They are indispensable when it comes to managing work flows in a highly asynchronous environment.
This talk covers patterns for using JavaScript Error (with a capital E) objects to build resilient applications, and introduce some modules that can be used to build errors with an elegant history of stack traces even through multiple asynchronous operations. Try/catch, callbacks, and other error handling mechanisms will be examined, revealing some potential deficiencies in the JavaScript language for dealing with errors.
Video: https://www.youtube.com/watch?v=PyCHbi_EqPs
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
Speaker: Andrzej Dyjak
Language: English
In recent years security industry started to grow fond of Apple’s iOS and OS X platforms. This talk will cover one of XNU's flagship debugging utilities: DTrace, a dynamic tracing framework for troubleshooting kernel and application problems on production systems in real time. It will be shown how it can be used in order to ease various tasks within the realm of dynamic binary analysis and beyond.
CONFidence: http://confidence.org.pl/
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
3. Is Node.js Single Threaded?
• Let’s run a simple http server
var http = require('http');
var server = http.createServer(function (req, res) {
// Request Handler
});
server.listen(3000);
“… Actually only your ‘userland’ code runs in one thread.
… Node.js in fact spins up a number of threads.”
- D. Khan, “How to track down CPU issues in Node.js”
01_server.js
4. Concurrency
“Concurrency is a way to structure a thing so that you can, maybe, use
parallelism to do a better job. But parallelism is not the goal of
concurrency; concurrency's goal is a good structure.”
- R. Pike, Golang co-inventor
TCP
Server
TCP
Server
Tasks spread over threads Tasks spread over time
Requests
Requests
t
t
5. Blocking and Non-Blocking I/O
• Simplified concepts of
▫ Blocking I/O
▫ Non-blocking I/O
• I/O multiplexing
▫ Reactor
▫ select() or poll()
▫ Event notification, synchronous event demux
7. Non-Blocking I/O Engine
• libuv
▫ Node.js, Luvit, …
▫ multi-platform support library with a focus on
asynchronous I/O
http://docs.libuv.org/
Linux OSX, BSDs SunOS Windows
10. Event Loop in Node.js (I)
// Entry point for new node instances, ...
static void StartNodeInstance(void* arg) {
// ...
{
SealHandleScope seal(isolate);
bool more;
do {
v8::platform::PumpMessageLoop(default_platform, isolate);
more = uv_run(env->event_loop(), UV_RUN_ONCE);
if (more == false) {
v8::platform::PumpMessageLoop(default_platform, isolate);
EmitBeforeExit(env);
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
more = true;
}
} while (more == true);
}
// ...
}
node.cc
11. Event Loop in Node.js (II)
Environment* CreateEnvironment(
Isolate* isolate,
uv_loop_t* loop,
// ...
const char* const* exec_argv)
{
// ...
uv_check_init(env->event_loop(), env->immediate_check_handle());
uv_unref(
reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
uv_idle_init(env->event_loop(), env->immediate_idle_handle());
uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
uv_check_init(env->event_loop(), env->idle_check_handle());
uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
// Register handle cleanups
env->RegisterHandleCleanup(
reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()),
HandleCleanup,
nullptr);
// ...
return env;
}
node.cc
Each node instance has its own event loop.
12. Put Tasks/Callbacks To Event Loop
• Non-blocking I/O APIs
▫ fs.readFile(path, cb)
• Timer Phase
▫ setTimeout(cb, time)
▫ setInterval(cb, time)
• Check Phase
▫ setImmediate(cb)
• At Each Phase End
▫ process.nextTick(cb)
▫ Microtasks (Promise)
┌───────────────────────┐
┌─>│ timers │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ I/O callbacks │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ idle, prepare │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ poll │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ check │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
└──┤ close callbacks │
└───────────────────────┘
process.nextTick()
Microtasks
[ ]
“Each phase has a FIFO queue of callbacks to execute.”
13. How Long a Tick Is?
“This is a tick: the synchronous invocation of zero or more callback
functions associated with any external events. Once the queue is
emptied out and the last function returns, the tick is over.”
- josh3736, “What exactly is a Node.js event loop tick?” Answered@stackoverflow
┌───────────────────────┐
┌─>│ timers │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ I/O callbacks │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ idle, prepare │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ poll │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ check │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
└──┤ close callbacks │
└───────────────────────┘
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
14. I/O Starvation
function crazy() {
console.log('Are you crazy?');
process.nextTick(function () {
crazy();
});
}
crazy();
[ ]
[ ]
[ ]
crazy()
nextTickQueue
“ … any time you call process.nextTick() in a given phase, all callbacks
passed to process.nextTick() will be resolved before the event loop
continues. … "starve" your I/O by making recursive process.nextTick()
calls, …”
18. .on( )
EventEmitter.prototype.addListener = function addListener(type, listener) {
var m;
var events;
var existing;
if (typeof listener !== 'function')
throw new TypeError('listener must be a function');
events = this._events;
// ...
if (!existing) {
// Optimize the case of one listener.
// Don't need the extra array object.
existing = events[type] = listener;
++this._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = [existing, listener];
} else {
// If we've already got an array, just append.
existing.push(listener);
}
// ...
}
return this;
};
event_name1: [ ]
event_name3: [ ]
event_name2:
events.js
19. .emit( )
EventEmitter.prototype.emit = function emit(type) {
// ...
events = this._events;
// ...
handler = events[type];
if (!handler)
return false;
// ...
switch (len) {
// fast cases
case 1:
emitNone(handler, isFn, this);
break;
case 2:
emitOne(handler, isFn, this, arguments[1]);
break;
// ...
// slower
default:
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
emitMany(handler, isFn, this, args);
}
// ...
return true;
};
function emitMany(handler, isFn, self, args) {
if (isFn)
handler.apply(self, args);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].apply(self, args);
}
}
event_name1: [ ]
event_name3: [ ]
event_name2:
events.js
21. Who Prints First?
console.log('<0> schedule with setTimeout in 1-sec');
setTimeout(function () { console.log('[0] setTimeout in 1-sec boom!'); }, 1000);
console.log('<1> schedule with setTimeout in 0-sec');
setTimeout(function () { console.log('[1] setTimeout in 0-sec boom!'); }, 0);
console.log('<2> schedule with setImmediate');
setImmediate(function () { console.log('[2] setImmediate boom!'); });
console.log('<3> A immediately resolved promise');
aPromiseCall().then(function () { console.log('[3] promise resolve boom!'); });
console.log('<4> schedule with process.nextTick');
process.nextTick(function () { console.log('[4] process.nextTick boom!'); });
function aPromiseCall () {
return new Promise(function(resolve, reject) { return resolve(); });
}
What if these things are arranged in an I/O callback?
02_prints.js
22. EventEmitter - Dead Loop
var EventEmitter = require('events');
var crazy = new EventEmitter();
crazy.on('event1', function () {
console.log('event1 fired!');
crazy.emit('event2');
});
crazy.on('event2', function () {
console.log('event2 fired!');
crazy.emit('event3');
});
crazy.on('event3', function () {
console.log('event3 fired!');
crazy.emit('event1');
});
crazy.emit('event1');
event1
event2event3
Synchronous Execution Loop
What if scheduled with…
• process.nextTick()
• setImmediate()
03_deadloop.js
23. Long-Running Tasks?
• How to deal with my long-running tasks?
▫ Cut it down or use a worker
• A ridiculous heavy task
function doHeavy () {
// Counts how many 1s occurred
var count = 0;
for (var i = 0; i < 1e8; i++) {
if (Math.round(Math.log(
Math.sqrt(Math.abs(Math.round(Math.random() * 1000)))
)) === 1)
count++;
}
return count;
}
setInterval(function () { console.log('I am not blocked'); }, 1000);
console.log(doHeavy()); // Takes around 10 seconds on my machine
04_heavy.js
24. Cut It Down (I)
function doNotSoHeavy (times) {
var count = 0;
for (var i = 0; i < times; i++) {
if (Math.round(Math.log(
Math.sqrt(Math.abs(Math.round(Math.random() * 1000)))
)) === 1)
count++;
}
return count;
}
function doHeavy() {
var total = 1e8,
cuts = 100,
counts = 0;
for (var i = 0; i < cuts; i++) {
counts = counts + doNotSoHeavy(total/cuts);
}
return counts;
}
setInterval(function () { console.log('I am not blocked'); }, 1000);
console.log(doHeavy()); // Takes around 10 seconds on my machine
Synchronous. Blocks?
04_heavy_cut_sync.js
25. Cut It Down (II)
function doHeavy(callback) {
var total = 1e8,
cuts = 100,
counts = 0,
remains = cuts;
for (var i = 0; i < cuts; i++) {
setImmediate(function () {
counts = counts + doNotSoHeavy(total/cuts);
remains--;
if (!remains) {
process.nextTick(function () {
callback(counts);
});
}
});
}
}
doHeavy(function (counts) {
console.log(counts);
});
Need a callback to get the asynchronous result
Asynchronous. Blocks?
04_heavy_cut_async1.js
26. Cut It Down (III)
function doHeavy(callback) {
var total = 1e8,
cuts = 100,
counts = 0,
remains = cuts;
function doPerLoopIter() {
setImmediate(function () {
counts = counts + doNotSoHeavy(total/cuts);
remains--;
if (!remains) {
process.nextTick(function () {
callback(counts);
});
} else {
doPerLoopIter();
}
});
}
doPerLoopIter();
}
doHeavy(function (counts) {
console.log(counts);
});
Asynchronous. Blocks?
04_heavy_cut_async2.js
27. Cut It Down (IV)
var heavyJobs = {
counts: 0,
queue: [],
_callback: null,
add: function (task) {
this.queue.push(task);
},
next: function (callback) {
var self = this,
task = this.queue.shift();
if (!task) return;
setImmediate(function () {
self.counts = self.counts + task();
if (self.queue.length === 0)
self._callback(self.counts);
else
self.next();
});
},
do: function (callback) {
this._callback = callback;
this.next();
}
};
var total = 1e8,
cuts = 100;
for (var i = 0; i < cuts; i++) {
heavyJobs.add(function () {
return doNotSoHeavy(total/cuts);
});
}
setInterval(function () {
console.log('I am not blocked');
}, 1000);
heavyJobs.do(function (counts) {
console.log(counts);
});
There are many ways to make your
heavy jobs happy…
04_heavy_queue.js
This example is for demonstrating
the idea. Not very thoughtful.
28. Run With Another Process
var fork = require('child_process').fork;
function doHeavyWithWorker(callback) {
var worker = fork('./heavy_jobs.js');
worker.once('message', function (counts) {
callback(counts);
});
}
setInterval(function () {
console.log('I am not blocked');
}, 1000);
doHeavyWithWorker(function (result) {
console.log(result.counts);
});
// heavy_jobs.js
function doHeavy () {
// Counts how many 1s occurred
var count = 0;
for (var i = 0; i < 1e8; i++) {
if (Math.round(Math.log(
Math.sqrt(Math.abs(
Math.round(Math.random() * 1000))
)
)) === 1)
count++;
}
return count;
}
var counts = doHeavy();
process.send({
counts: counts
});
fork() establishes the IPC channel between parent and child for your convenience to
run your node.js code. There are others ways to do such a job with child_process.
05_heavy_fork.js heavy_jobs.js