How to synchronize access to private members of a javascript object
Asked Answered
H

1

13

I have a Javascript object created as follows:

var ccStatTracker = (function (){
  ccmap:{
    "1":["1","2","3","4"],
    "2":["4","5"];       
  }

  return {
    modifyCCMap: function (){
      // Code which takes following actions: 
      // - adds/removes keys.
      // - modifies arrays stored as values against the keys in the map.  
    }  
  }
)();

I have a DHTMLXGrid component which displays grid in the form of rows and columns. When I edit any cell in the grid, "onEditCell" event is called. Now, I want to call ccStatTracker.modifyCCMap() from an event handler function attached to "onEditCell" event. As I go on modifying the cells, this event will be called asynchronously which will in turn call a function "modifyCCMap" which will modify private member "CCMap" of my Javascript object. So the latest state of my CCMap as seen by two calls might be different right? So what is the best way to handle this? Is there something as "Synchronized" in Javascript as in Java?

Please help me as it will determine the approach we want to take for implementing this.

Harber answered 9/6, 2012 at 11:16 Comment(5)
ASAP won't make it more ASAP :)Fu
asynchronously does not mean concurrently!Proffitt
@Fu : hmm.just gave it a try.Harber
@Felix Kling : thats piece of info is really helpful.Harber
@Felix Kling: so in above senario, if user goes on editing the cells,All eventhandlers that are fired will run one after the other(not concurrently),even if they are initiated asynchronously!! Right?Harber
M
30

JavaScript is single-threaded (s aside for a moment), nothing happens asynchronously (or everything for that matter) - all code: event handlers, timeouts, callbacks, etc. - run in the same thread, one after another.

Thus you don't need any synchronization in JavaScript. Any given piece of code in JavaScript is guaranteed to be executed by only a single thread. How cool is that?

See also

Mcgough answered 9/6, 2012 at 11:20 Comment(4)
so in above senario, if user goes on editing the cells,All eventhandlers that are fired will run one after the other(not concurrently),even if they are initiated asynchronously!! Right?Harber
@ShaileshVaishampayan: correct. Events will be queued and fired one after another. Even timeouts scheduled to fire at the same time will queue up.Mcgough
First, ECMAScript doesn't require JS to be executed in a single thread. Second, setTimeout() etc. are specified by HTML5 where it is clearly defined that the handler can indeed run in a parallel thread: html.spec.whatwg.org/multipage/infrastructure.html#in-parallelArdeliaardelis
@Ardeliaardelis so what additional precautions do we need to take?Pteridology

© 2022 - 2024 — McMap. All rights reserved.