javascriptspecificationsecmascript-2017

What's the actual use of the Atomics object in ECMAScript?


The ECMAScript specification defines the Atomics object in the section 24.4.

Among all the global objects this is the more obscure for me since I didn't know about its existence until I didn't read its specification, and also Google hasn't many references to it (or maybe the name is too much generic and everything gets submerged?).

According its official definition

The Atomics object provides functions that operate indivisibly (atomically) on shared memory array cells as well as functions that let agents wait for and dispatch primitive events

So it has the shape of an object with a number of methods to handle low-level memory and regulate the access to it. And also its public interface makes me suppose it. But what's the actual use of such object for the end-user? Why is it public? Are there some examples where it can be useful?

Thank you


Solution

  • Atomics are for synchronising WebWorkers that share memory. They cause memory access into a SharedArrayBuffer to be done in a thread safe way. Shared memory makes multithreading much more useful because:

    Example:

    var arr = new SharedArrayBuffer(1024);
    
    // send a reference to the memory to any number of webworkers
    workers.forEach(worker => worker.postMessage(arr));
    
    // Normally, simultaneous access to the memory from multiple threads 
    // (where at least one access is a write)
    // is not safe, but the Atomics methods are thread-safe.
    // This adds 2 to element 0 of arr.
    Atomics.add(arr, 0, 2)
    

    SharedArrayBuffer was enabled previously on major browsers, but after the Spectre incident it was disabled because shared memory allows implementation of nanosecond-precision timers, which allow exploitation of spectre.

    In order to make it safe, browsers need to run pages a separate process for each domain. Chrome started doing this in version 67 and shared memory was re-enabled in version 68.