3

Here is the scene about my problem.

I make a var dataCache, which buffers the data I achieve from remote server. I update dataChache every 30s, like this,

setInterval(function(){
      instance.loadJsonFromRemote(configuration.dataUrl,function(data){
        instance.dataCache = data;
});
}, 30000);

and dataCache probably would be accessed exactly at the same time when it's being updated.

For example,

var cool = instance.dataCache.cool

the code above runs while the data updating code runs,

instance.dataCache = data;

I guess the possible solution would be lock dataCache up while it is being accessed, if no one accesses it, it can be set.

I probably need something like lock in C#, but I don't really know how to do it in JavaScript, or maybe it is not even a problem in JavaScript, coz JS is single threaded and it works fine. I'm not very familiar with JS.

Ranger 22
  • 415
  • 4
  • 19
  • 3
    "JS is single threaded and it works fine" yes. You don't need to lock the var – R3tep May 10 '17 at 13:35
  • 1
    Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop. You are right, there is no need for something like a lock. – Felix Kling May 10 '17 at 13:38
  • Though there is also this: http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded I don't know how much it may affect you in your case. Posted it just in case. – Aleksander Stelmaczonek May 10 '17 at 13:44

2 Answers2

1

There is no lock mechanism because javascript executes as single threaded.

The reason for confusion for people who came from a multi-threaded environment is that javascript always works like "async" way. But that is not really the case.

Javascript works with "callbacks" internally when some event is happened it will execute its callbacks that can be a bit tricky for a Java/.Net developer. Javascript always works on a single thread and nothing executes simultaneously, it has "javascript execution cycle" (See For Event Loop) that can be said a simple while(1) {} code executes code over and over again in each cycle your callbacks are initiated and etc.

The only possible solution for your case would be a callback from the setTimeout function that will trigger your update scenario.

0

There might be at least two options:

  1. If you are the only user of instance, you always can add a flag to instance before doing an async call, like instance.state = "updating" or instance.locked = true and reset the value in the callback or promise's resolve. This is not save from manipulation, but should be feasable and easy to do.
  2. If you want to make sure nobody will modify the object in the meantime, save the original reference to instance into a temporary variable, replace the current object with an empty object, a placeholder object or (the propably most elegant way) a freezed clone of the original instance. After update, reset the reference to the original instance.
RiZKiT
  • 2,107
  • 28
  • 23