Is JavaScript guaranteed to be single-threaded?
Asked Answered
M

13

692

JavaScript is known to be single-threaded in all modern browser implementations, but is that specified in any standard or is it just by tradition? Is it totally safe to assume that JavaScript is always single-threaded?

Melanson answered 29/4, 2010 at 0:24 Comment(3)
In the context of browsers, probably. But some programs allow you to treat JS as a top level lang and provide bindings for other C++ libs. For instance, flusspferd (C++ bindings for JS - AWESOME BTW) was doing some stuff with multithreaded JS. It's up to the context.Ectomere
This is a must read: developer.mozilla.org/en/docs/Web/JavaScript/EventLoopRooky
@Rooky You've created a cyclic reference! That article links to this question which links to…Baggage
Q
662

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">

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

var l= document.getElementById('log');
document.getElementById('act').onclick= function() {
    l.value+= 'alert in\n';
    alert('alert!');
    l.value+= 'alert out\n';
};
window.onresize= function() {
    l.value+= 'resize\n';
};
<textarea id="log" rows="20" cols="40"></textarea>
<button id="act">alert</button>

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

Qoph answered 29/4, 2010 at 1:51 Comment(21)
I don't understand the issue with the focus/blur behaviour -- to me that seems totally expected. When something is focused or blurred I want to know ASAP. But, I do understand why you mentioned it -- it is relevant to the topic :)Yolk
@J-P: Personally I don't want to know straight away because it means I have to be careful that my code is re-entrant, that calling my blur code won't affect state that some outer code is relying on. There are too many cases where blurring is an unexpected side-effect to necessarily catch every one. And unfortunately even if you do want it, it's not reliable! IE fires blur after your code returns control to the browser.Qoph
In my experience odd behavior crops up when manipulating the DOM aswell, I seem to recall a problem I had where I assumed that after manipulating lots of elements from the DOM in a function they would be gone/added, not so when I called the next maniplating function :/Glum
+1 - I've been messing around with modal windows in IE whilst debugging before and moved one only to find another behind it, closed that one and found another behind that, and so on and so forth. It was rather fun to watch the "aero" shadowing around the windows get slightly lighter as I clicked away the boxes ;-(Subliminal
Javascript is single threaded. Halting your execution on alert() doesn't mean the event thread stops pumping events. Just means your script is sleeping while the alert is on the screen, but it has to keep pumping events in order to draw the screen. While an alert is up the event pump is running which means it's entirely correct to keep sending out events. At best this demonstrates a cooperative threading that's can happen in javascript, but all of this behavior could be explained by a function simply appending an event to the event pump to be processed at a later point vs. doing it now.Neom
But, remember cooperative threading is still single threaded. Two things can't happen simultaneously which is what multi-threading allows and injects non-determinism. All of what was described is deterministic, and it's a good reminder about these types of issues. Good job on the analysis @QophNeom
@Qoph - your initial login / focus() / logout example is interesting, but is that behaviour really so strange? With a code-triggered focus I would expect it to be similar to login / doSomething() / logout, and finish the middle bit before getting to the logout.Privett
Chubbard is right: JavaScript is single threaded. This is not an example of multithreading, but rather synchronous message dispatch in a single thread. Yes, it's possible to pause the stack and have event dispatch continue (e.g. alert()), but the kinds of access problems that occur in true multithreaded environments simply can't happen; for example, you will never have a variable change values on you between a test and an immediately subsequent assignment, because your thread cannot be arbitrarily interrupted. I fear that this response is only going to cause confusion.Amorete
@Kris: see the discussion of the watchdog in modern browsers, which can indeed arbitrarily interrupt your thread of execution. If you have a long-running script and you are unlucky it is eminently possible to have a variable change between being tested and subsequent assignment.Qoph
Do you have a link to that discussion? I should probably clarify that while it is possible to have the JavaScript thread interrupted (obviously the host application can have multiple threads) the question is whether one thread running JavaScript can be interrupted by another thread running JavaScript against the same global context. It might be possible to build an application that does this by subverting the intent of the JavaScript engine, but this example does not illustrate that.Amorete
This description isn't really one of a multithreadded environment, though, where execution happens literally in parallel. Rather, it's simply evidence that any point you call a blocking function which waits for user input, the browser re-enters its event loop.Uncurl
Yes, but given that a blocking function that waits for user input can happen in-between any two statements, you have potentially all the consistency problems that OS-level threads bring you. Whether the JavaScript engine actually runs in multiple OS threads is of little relevance.Qoph
@Qoph event loop reentrancy brings you very different problems and solutions than shared memory concurrency. Assuming they are the same will rapidly get you into trouble. A simple example is trying use to a mutex to make something "event loop reentrant"-safe. If it's a reentrant mutex it does nothing, if it's not reentrant you end up deadlocking yourself. Event loop reentrancy has plenty of pitfalls, but they are not the same pitfalls.Epicrisis
I just tested your example with an alert on Chrome 27.0.1453.110 on Windows and couldn't reproduce the behavior you describe; if I change my screen resolution while the alert is active, I get "alert in alert out resize resize" in the textarea. Perhaps these issues have been fixed lately?Winy
This answer is misleading at best. It describes that JavaScript may be asynchronous, which is true. But basic JavaScript without WebWorkers is never multithreaded. See Már Örlygsson's answer below.Depraved
Well, okay, so you could say "JavaScript is single threaded", but you can't say "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"; and you apparently can't even say "you remain completely in control until you call a function that pumps events or [existing reason]". (At least, not if that thing about the "unresponsive script" warning is still true.) So perhaps the first paragraph should be rewritten a little, to say something like "Yes, but that's not as helpful as you might think."Openeyed
Chrome version 63.0.3239.132: The behavior described still stands correct for the manual .focus() call, but not for alert()s or pop-ups, for those 2, log in log out blur will be printed out.Jabber
Sorry, this widely up-voted answer is not correct, certainly not regarding modern versions of Chrome. The "immediate" events described are called, immediately and synchronously, not by the event loop. As mentioned by @doubleOrt, with the call to alert(), the messages show execution of "blur" only after the alert() is done. See jsfiddle.net/xewfpcxk. This is considered a fundamental characteristic of JavaScript, often referred to as "run to completion".Stopping
This post is entirely wrong on Firefox, where I get "log in, log out", and "alert in, alert out" (no resize), and if I stop and endless loop, the endless loop halts and onResize doesn't run after. It's partially wrong on Chrome, where I get "log in, blur, log out" and "alert in, alert out, resize, resize".Chemarin
Interestingly, I get alert in alert out and no resize shows up in the text area. Seems things keep changing (hopefully for the better!).Gal
Unlike "native" events, which are fired by the DOM and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers will execute and return before the code continues on after the call to dispatchEvent(). developer.mozilla.org/en-US/docs/Web/API/EventTarget/…Headsman
H
122

I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.

Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.

(Note to others commenters: Even though setTimeout/setInterval, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)

Horoscopy answered 29/4, 2010 at 0:28 Comment(2)
I agree. If multi-threading is ever added to Javascript in the browser, it will be via some explicit API (e.g. Web Workers) just like it is with all imperative languages. That's the only way that makes sense.Tulle
Note that there is a single. main JS thread, BUT some things are run in the browser in parallel. It's not just an impression of multi-threadedness. Requests are actually run in parallel. The listeners you define in JS are run one-by-one, but requests are truly parallel.Trantrance
K
15

Yes, although you can still suffer some of the issues of concurrent programming (mainly race conditions) when using any of the asynchronous APIs such as setInterval and xmlhttp callbacks.

Karyogamy answered 29/4, 2010 at 0:28 Comment(0)
S
12

I would say that the specification does not prevent someone from creating an engine that runs javascript on multiple threads, requiring the code to perform synchronization for accessing shared object state.

I think the single-threaded non-blocking paradigm came out of the need to run javascript in browsers where ui should never block.

Nodejs has followed the browsers' approach.

Rhino engine however, supports running js code in different threads. The executions cannot share context, but they can share scope. For this specific case the documentation states:

..."Rhino guarantees that accesses to properties of JavaScript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time.If two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables."

From reading Rhino documentation I conclude that that it can be possible for someone to write a javascript api that also spawns new javascript threads, but the api would be rhino-specific (e.g. node can only spawn a new process).

I imagine that even for an engine that supports multiple threads in javascript there should be compatibility with scripts that do not consider multi-threading or blocking.

Concearning browsers and nodejs the way I see it is:

    1. Is all js code executed in a single thread? : Yes.
    1. Can js code cause other threads to run? : Yes.
    1. Can these threads mutate js execution context?: No. But they can (directly/indirectly(?)) append to the event queue from which listeners can mutate execution context. But don't be fooled, listeners run atomically on the main thread again.

So, in case of browsers and nodejs (and probably a lot of other engines) javascript is not multithreaded but the engines themselves are.


Update about web-workers:

The presence of web-workers justifies further that javascript can be multi-threaded, in the sense that someone can create code in javascript that will run on a separate thread.

However: web-workers do not curry the problems of traditional threads who can share execution context. Rules 2 and 3 above still apply, but this time the threaded code is created by the user (js code writer) in javascript.

The only thing to consider is the number of spawned threads, from an efficiency (and not concurrency) point of view. See below:

About thread safety:

The Worker interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.


P.S.

Besides theory, always be prepared about possible corner cases and bugs described on the accepted answer

Sharonsharona answered 12/12, 2016 at 14:37 Comment(0)
E
10

Yes, although Internet Explorer 9 will compile your Javascript on a separate thread in preparation for execution on the main thread. This doesn't change anything for you as a programmer, though.

Extravagance answered 29/4, 2010 at 0:30 Comment(0)
S
7

JavaScript/ECMAScript is designed to live within a host environment. That is, JavaScript doesn't actually do anything unless the host environment decides to parse and execute a given script, and provide environment objects that let JavaScript actually be useful (such as the DOM in browsers).

I think a given function or script block will execute line-by-line and that is guaranteed for JavaScript. However, perhaps a host environment could execute multiple scripts at the same time. Or, a host environment could always provide an object that provides multi-threading. setTimeout and setInterval are examples, or at least pseudo-examples, of a host environment providing a way to do some concurrency (even if it's not exactly concurrency).

Stunk answered 29/4, 2010 at 1:9 Comment(0)
S
7

Actually, a parent window can communicate with child or sibling windows or frames that have their own execution threads running.

Spinning answered 29/4, 2010 at 4:3 Comment(0)
I
6

@Bobince is providing a really opaque answer.

Riffing off of Már Örlygsson's answer, Javascript is always single-threaded because of this simple fact: Everything in Javascript is executed along a single timeline.

That is the strict definition of a single-threaded programming language.

Italianism answered 25/5, 2016 at 22:22 Comment(0)
D
5

No.

I'm going against the crowd here, but bear with me. A single JS script is intended to be effectively single threaded, but this doesn't mean that it can't be interpreted differently.

Let's say you have the following code...

var list = [];
for (var i = 0; i < 10000; i++) {
  list[i] = i * i;
}

This is written with the expectation that by the end of the loop, the list must have 10000 entries which are the index squared, but the VM could notice that each iteration of the loop does not affect the other, and reinterpret using two threads.

First thread

for (var i = 0; i < 5000; i++) {
  list[i] = i * i;
}

Second thread

for (var i = 5000; i < 10000; i++) {
  list[i] = i * i;
}

I'm simplifying here, because JS arrays are more complicated then dumb chunks of memory, but if these two scripts are able to add entries to the array in a thread-safe way, then by the time both are done executing it'll have the same result as the single-threaded version.

While I'm not aware of any VM detecting parallelizable code like this, it seems likely that it could come into existence in the future for JIT VMs, since it could offer more speed in some situations.

Taking this concept further, it's possible that code could be annotated to let the VM know what to convert to multi-threaded code.

// like "use strict" this enables certain features on compatible VMs.
"use parallel";

var list = [];

// This string, which has no effect on incompatible VMs, enables threading on
// this loop.
"parallel for";
for (var i = 0; i < 10000; i++) {
  list[i] = i * i;
}

Since Web Workers are coming to Javascript, it's unlikely that this... uglier system will ever come into existence, but I think it's safe to say Javascript is single-threaded by tradition.

Douglass answered 12/2, 2012 at 22:2 Comment(2)
Most language definitions are designed to be effectively single-threaded though, and state that multithreading is permitted as long as the effect is identical. (e.g. UML)Quincuncial
I have to agree with the answer simply because the current ECMAScript makes no provision (although arguably I think the same can be said for C) for concurrent ECMAScript execution contexts. Then, like this answer, I'd argue that any implementation that does have concurrent threads being able to modify a shared state, is an ECMAScript extension.Fussbudget
G
4

Javascript engine must be single threaded, but Javascript runtime doesn't need to be single threaded.

Now what is Javascript engine? That is the interpreter which executes actual JS code. Engine needs a host. It can't run on its own. The host is Javascript runtime.

For example, V8 engine which runs in Chrome browser is single threaded. Chrome browser is a runtime & it has other processes/threads to support V8 engine.

You can check this article where it is explained beautifully. If it helps, don't forget to comeback & upvote :)

Gibberish answered 18/6, 2022 at 6:52 Comment(1)
How does a single threaded JS engine interpret multitreading language features such as SharedArrayBuffer and Atomics?Lemmon
E
3

Well, Chrome is multiprocess, and I think every process deals with its own Javascript code, but as far as the code knows, it is "single-threaded".

There is no support whatsoever in Javascript for multi-threading, at least not explicitly, so it does not make a difference.

Encephalogram answered 29/4, 2010 at 0:28 Comment(0)
L
3

I've tried @bobince's example with a slight modifications:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <textarea id="log" rows="20" cols="40"></textarea>
    <br />
    <button id="act">Run</button>
    <script type="text/javascript">
        let l= document.getElementById('log');
        let b = document.getElementById('act');
        let s = 0;

        b.addEventListener('click', function() {
            l.value += 'click begin\n';

            s = 10;
            let s2 = s;

            alert('alert!');

            s = s + s2;

            l.value += 'click end\n';
            l.value += `result = ${s}, should be ${s2 + s2}\n`;
            l.value += '----------\n';
        });

        window.addEventListener('resize', function() {
            if (s === 10) {
                s = 5;
            }

            l.value+= 'resize\n';
        });
    </script>
</body>
</html>

So, when you press Run, close alert popup and do a "single thread", you should see something like this:

click begin
click end
result = 20, should be 20

But if you try to run this in Opera or Firefox stable on Windows and minimize/maximize window with alert popup on screen, then there will be something like this:

click begin
resize
click end
result = 15, should be 20

I don't want to say, that this is "multithreading", but some piece of code had executed in a wrong time with me not expecting this, and now I have a corrupted state. And better to know about this behavior.

Liquefy answered 26/7, 2016 at 12:13 Comment(0)
Y
-6

Try to nest two setTimeout functions within each other and they will behave multithreaded (ie; the outer timer won't wait for the inner one to complete before executing its function).

Yolk answered 15/11, 2010 at 19:56 Comment(1)
chrome does this the right way, dunno where @Yolk sees it being multithreaded...: setTimeout(function(){setTimeout(function(){console.log('i herd you liek async')}, 0); alert('yo dawg!')}, 0) (for the record, yo dawg should ALWAYS come first, then the console log output)Tzong

© 2022 - 2024 — McMap. All rights reserved.