I have given below simplified JavaScript problem.
var PROJ=(function(){
var tags={},
var lock=true;
function onLoadComplete(){}
this.Tag = function(userConfig,callBack){
function loadConfig(){
lock=false;
/* Do something privately having lock with me */
lock=true;
}
this.load(){
if(lock) loadConfig();
else setTimeout(load,1000);
// PROBLEM is this(above) load is calling OUTER load..!
}
return this;
};
this.load(){
var cb=onLoadComplete;
tags[uniqueID]=new Tag(userConfig,cb);
tags[uniqueID].load();
}
}).load();
I am trying to implement JavaScript locks here. Three JavaScript Tag objects are created. [ new Tag() ]These objects share and modify some public data available in PROJ.
I want to give access to public data when lock has been released by executing Tag. This load mentioned in setTimeout() is calling load() of PROJ.
I am presuming that the code actually looks like this:
Since JavaScript is single threaded, it is not possible for the
loadfunction to be invoked whileloadConfigis still running. This means that it is not possible for thelockvariable to befalseinsideload, unless:returnstatement inloadConfigwhich returns execution beforelockis set totrue.For the latter case, you can use the
try/finallyblock to make sure thatlockis reset in case of an exception:The bottom line is,
lockis not needed at all and can be removed completely. There is no wayloadcould run concurrently withloadConfig.