How Is JavaScript Single Threaded

how javascript single threaded and asynchronous

It's true that JavaScript is (now) specified to have only a single active thread per realm (roughly: a global environment and its contents).¹ But I wouldn't call it "single-threaded;" you can have multiple threads via workers. They do not share a common global environment, which makes it dramatically easier to reason about code and not worry about the values of variables changing out from under you unexpectedly, but they can communicate via messaging and even access shared memory (with all the complications that brings, including the values of shared memory slots changing out from under you unexpectedly).

But running on a single thread and having asynchronous callbacks are not at all in conflict. A JavaScript thread works on the basis of a job queue that jobs get added to. A job is a unit of code that runs to completion (no other code in the realm can run until it does). When that unit of code is done running to completion, the thread picks up the next job from the queue and runs that. One job cannot interrupt another job. Jobs running on the main thread (the UI thread in browsers) cannot be suspended in the middle (mostly²), though jobs on worker threads can be (via Atomics.wait). If a job is suspended, no other job in the realm will run until that job is resumed and completed.

So for instance, consider:

console.log("one");
setTimeout(function() {
console.log("three");
}, 10);
console.log("two");

Can someone please Explain me how is Nodejs single threaded being Asynchronous

"Single threaded" in this case means that it runs YOUR Javascript in a single thread. That means that it runs a piece of your Javascript until it returns control back to the system and only then can it run the code attached to some other event. No two pieces of your Javascript are ever actually executing at the same time.

FYI, we're ignoring WorkerThreads here for the purposes of this discussion which are a purposeful way to run multiple threads of Javascript, but are not involved in the general asynchronous architecture.

Asynchronous operations are ALL implemented in native code (usually C/C++ code) by nodejs. They are things such as timers, networking operations, disk operations, etc... That native code (mostly in a cross platform library called libuv) has interfaces in Javascript that allows you to call them such as http.request() or fs.read(), but the underlying core implementation of those functions is in native code. The native code for those operations may or may not actually use OS threads in its implementation. But, those threads are entirely hidden from the Javascript code.

For example, networking operations in nodejs do not use threads. They use natively asynchronous APIs in the operating system that allow them to be notified when a network operation has completed without blocking or spinning and waiting for it. Other asynchronous operations such as file operations do actually use a pool of native OS threads to "simulate" an asynchronous architecture.

So, while your Javascript is run as single threaded, multiple asynchronous operations can be in process at once. If you look at this code:

const fsp = require('fs').promises;

Promise.all([fsp.readFile("filea.txt"), fsp.readFile("fileb.txt")]).then(results => {
console.log(results[0]);
console.log(results[1]);
}).catch(err => {
console.log(err);
});

This will read two files in parallel and tell you when the data from both files is available. While your Javascript still runs as single threaded, the underlying file operations are using OS-level threads and the disk operations are running in separate threads. So, it's only your actual Javascript that is single threaded, not necessarily the underlying asynchronous operations.

Fortunately, you can generally avoid entirely the concurrency headaches of multi-threaded programming because two pieces of your own Javascript are never running at the same moment in time. Thus, you don't need mutexes or other concurrency devices just to write to variables safely. The details of thread use are abstracted behind the asynchronous interfaces. And, the event driven nature of how nodejs handles the completion of these asynchronous interfaces dictates that one piece of Javascript will run to complete before the next completion event can be processed that has the next asynchronous result in it.

Is JavaScript single threaded?

Javascript isn't inherently single-threaded or multi-threaded as a language. There are Javsacript environments that don't offer Javascript threads and environments that do offer Javascript threads. The language itself doesn't specify single-threadedness or multi-threadedness. Instead, it's up to the environment whether it wants to make threads of Javascript available.

So, to your specific question:

Is JavaScript single threaded?

No. It's not specifically single threaded or multiple threaded. The language specification doesn't require either. The threading of Javascript is up to the run-time environment to implement. It so happens that both the browser and node.js started out without Javascript threads and an event-driven architecture which led to this notion that there are no threads in a Javascript environment, but there ARE. They now both offer Javascript threads (WebWorkers in the browser and WorkerThreads in node.js).

The Javascript specification offers some features that are useful in multi-threaded environments such as SharedArrayBuffer objects and Atomics and environments that offer threading provide additional libraries. So, the current language specification recognizes some of the needs of multi-threading and provides some tools for it, though there is no specific requirement that a Javascript runtime has or doesn't have threads. It's up to the run-time whether they want to offer that capability to run multiple Javascript threads of execution in parallel or not.

What does it mean when they say JavaScript is single-threaded?

JavaScript, the language, is nearly silent on the topic of threading. Whether it's single- or multi-threaded is a matter of the environment in which it runs. There are single-threaded JavaScript environments, and multi-threaded JavaScript environments. The only real requirement the specification makes is that a thread have a job queue and that once a job (a unit of code to run, like a call to an event handler) is started, it runs to completion on the thread before another job from that queue is started. That is, JavaScript has run-to-completion semantics.

JavaScript on browsers isn't single-threaded and hasn't been for years. There is one main thread (the thread the UI is handled on), and any number of web worker threads. The web workers don't have direct access to the UI, they send messaegs to the UI thread, and it does the UI updates. The threads don't directly share data, they share data explicitly via messaging. This separation makes programming multi-threaded code dramatically simpler and less error-prone than if multiple threads had access to the UI and the same common data area. (Writing correct multi-threaded code where any thread can access anything at any time is hard.)

Outside the browser, JavaScript in NodeJS is run on a single thread. There was a fork of Node to add multi-threading, but I don't think it ever went anywhere.

JavaScript on the JVM (Rhino, Nashorn) has always been multi-threaded, supported by the threading facilities of the JVM.

How is Javascript single threaded?

JavaScript (in browsers) doesn't run concurrently2.

At most one of the setTimeout callbacks can execute at a time - as there is one JavaScript execution context or "thread".

However, the "next scheduled timeout" to run is always run .. next. The "4" runs before the "2" callback because it was scheduled to run sooner. The timeouts were effectively scheduled from the same time (none of the operations were blocking), but "2" had a much longer interval.

The underlying implementation may use threads1 - but JavaScript in the same global context doesn't run concurrently and guarantees consistent and atomic behavior between all callbacks.


1 Or it may not; this can be handled without any threads in a select/poll implementation.

2 In the same context: i.e. Tab/Window, WebWorker, host Browser Control. For example, while WebWorkers are run concurrently they do so in different contexts and follow the same asynchronous model (eg. as used by timers).

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

var l= document.getElementById('log');var i= document.getElementById('inp');i.onblur= function() {    l.value+= 'blur\n';};setTimeout(function() {    l.value+= 'log in\n';    l.focus();    l.value+= 'log out\n';}, 100);i.focus();
<textarea id="log" rows="20" cols="40"></textarea><input id="inp">

Since JavaScript is single-threaded, how are web workers in HTML5 doing multi-threading?

As several comments have already pointed out, Workers really are multi-threaded.

Some points which may help clarify your thinking:

  • JavaScript is a language, it doesn't define a threading model, it's not necessarily single threaded
  • Most browsers have historically been single threaded (though that is changing rapidly: IE, Chrome, Firefox), and most JavaScript implementations occur in browsers
  • Web Workers are not part of JavaScript, they are a browser feature which can be accessed through JavaScript

Javascript and its one single thread

It helps to understand that there is a call stack and an event queue. Call stack processes one thing at a time and represents the single threaded nature of JavaScript. The event loop is sort of queue where asyschronus methods are placed and then moved to call stack for processing when they are complete and when the call stack is empty.

Question: it has to wait for the single thread to end the execution of the first callback method, right?

Answer: Yes that is correct.

Question: Its impossible then that the code for the callback method it being executed at the same time for two threads.

Answer: Yes that's also correct

Question: Its like having the functionality synchronized from java in javascript for methods

Answer: That's not correct becasue of event loop and call stack.

Do check out this video https://www.youtube.com/watch?v=8aGhZQkoFbQ on youtube for a detailed explanation.



Related Topics



Leave a reply



Submit