Saturday, March 21, 2009

Merging Multiple AJAX threads using a "Joining Mutex"

I had previously posted this article with a snippet of example code. That blog entry was accidently deleted so I am reposting an update version of it now.

What is a "Joining Mutex" and why would you need it?

var AfterAllThreadsExecute = function() { alert("Hello World");}

for(var i=0; i < records.length; i++) {
        // dispatchAjaxCall(ThreadMutexHandle, recordId)
 dispatchAjaxCall(JoiningMutex.contextJoinCreate('TestContext',AfterAllThreadsExecute, records[i].ID);
}


within the dispatchAjaxCall(myMutexHandle) {

 // do AJAX stuff here ...

 // now signal to the Mutex (via our reference handle) that this thread has finish running
 myMutexHandle.ThreadFinished();
}
A listing of the initial code is below. The latest code is used within the i2b2 web client in the i2b2/hive/hive_helpers.js file and can be found at https://github.com/i2b2/i2b2-webclient/blob/master/js-i2b2/hive/hive_helpers.js
// created this object to allow the joining of forked execution paths (Waiting for Multiple AJAX calls)
JoiningMutex = { 
 _contexts: {},
 _contextGenID: 0,
 _createContextProxy: function(contextRef) {
  // create a proxy object (via closure) to encapsulate data 
  // and route actions to the JoinMutex singleton
  var cl_JoinMutextRef = contextRef;
  function JoiningMutexContextProxy() {
   this._JoiningMutexContext = cl_JoinMutextRef;
   this._alreadyRun = false;
   this.name = function() { return this._JoiningMutexContext.name; };
   this.openThreads = function() { return this._JoiningMutexContext.openThreads; };
   this.executeOnce = function() { return this._JoiningMutexContext.executeOnce; };
   this.executionCount = function() { return this._JoiningMutexContext.executionCount; };
   this.isActive = function() { return this._JoiningMutexContext.active; };
   this.ThreadFinished = function() {
    if (!this._JoiningMutexContext.active) {
     return {error: true, errorObj: undefined, errorMsg: 'JoiningMutexProxy.ThreadFinished() failed because the giving context is no longer active'};
    }
    if (this._JoiningMutexContext._alreadyRun) {
     return {error: true, errorObj: undefined, errorMsg: 'JoiningMutexProxy.ThreadFinished() failed because the MutexProxy has already been run'};
    }
    if (this._JoiningMutexContext.openThreads > 0) {
     this._JoiningMutexContext.openThreads--;
     this._alreadyRun = true;
     if (this._JoiningMutexContext.openThreads == 0) {
      // all threads finished
      if (this._JoiningMutexContext.executeOnce) {
       // this is going to be our only run of the callback function
       this._JoiningMutexContext.active = false;
      }
      this._JoiningMutexContext.executionCount++;
      this._JoiningMutexContext.callbackFinished();
      return true;
     } else {
      // everything is OK but there are still outstanding threads to finish
      return false;
     }
    } else {
     return {error: true, errorObj: undefined, errorMsg: 'JoiningMutexProxy.ThreadFinished() failed because there are no outstanding thread executions'};
    }
   };
  }
  return new JoiningMutexContextProxy;
 },
 contextCreate: function(sContextName, fZeroRunFunction, bSingleRun) {
  // make sure context is new
  var validName = sContextName;
  try {
   if (!validName) {
    this._contextGenID++;
    validName = "AUTOGEN-"+this._contextGenID;
   }
   if (this._contexts[validName]) {
    return {error: true, errorObj: undefined, errorMsg: 'JoiningMutex.contextCreate() failed because the giving context name already exists'};
   }
   // verify that the name can be used as an object identifier (with throw an error if invalid)
   this._contexts[validName] = true;
   delete this._contexts[validName];
  } catch(e) {
   return {error: true, errorObj: e, errorMsg: 'an error occurred within JoiningMutex.contextCreate()'};
  }
  // create new context object
  function JoiningMutexContext(inName, inFinishFunction, inSingleExecution) {
   this.name = inName;
   this.callbackFinished = inFinishFunction;
   this.openThreads = 0;
   this.executeOnce = inSingleExecution;
   this.executionCount = 0;
   this.active = true;
  }
  var bSingleRun = Boolean.parseTo(bSingleRun);
  this._contexts[validName] = new JoiningMutexContext(validName, fZeroRunFunction, bSingleRun);
  // add ourselves to the thread count
  var cl_JoinMutextRef = this._contexts[validName];
  cl_JoinMutextRef.openThreads++;
  return this._createContextProxy(cl_JoinMutextRef);
 },
 contextJoin: function(sContextName) {
  // make sure context already exists
  var validName = sContextName;
  if (!this._contexts[validName]) {
   return {error: true, errorObj: undefined, errorMsg: 'JoiningMutex.contextCreate() failed because the context name does not exist'};
  }
  var cl_JoinMutextRef = this._contexts[validName];
  // Add this thread to the count
  cl_JoinMutextRef.openThreads++;
  return this._createContextProxy(cl_JoinMutextRef);
 },
 contextJoinCreate: function(sContextName, fZeroRunFunction, bSingleRun) {
  // Join context or create it if it exists
  var ctx = false;
  if (!sContextName || !this._contexts[sContextName]) {
   ctx = this.contextCreate.call(this, sContextName, fZeroRunFunction, bSingleRun);
  } else {
   ctx = this.contextJoin.call(this, sContextName);
  }
  return ctx;
 },
 contextDestroy: function(sContextName) {
  if (!sContextName || !this._contexts[sContextName]) {
   return false;
  } else {
   // Garbage collection will not execute until all 
   // the JoiningMutexContextProxy are deleted so 
   // invalidate the context as well as delete it!
   this._contexts[sContextName].active = false;
   this._contexts[sContextName].callbackFinished = function() { return null; };
   delete this._contexts[sContextName];
   return true;
  }
 }
};

Wednesday, October 8, 2008

Cute Thoughts

A few original quotes by myself and others...


"A candy bowl on a desk is the cubicle farm's equivalent of a salt lick." -HCEO

"Wall St has the best of both worlds, privatized profits and socialized losses" -unknown

Tuesday, September 30, 2008

Yet another reason Monster.com is not worth your time...

This email I got today provides me yet another reason Monster.com is not worth my time...



Great news! We have found new jobs matching your job search criteria!

Here are the results that were found on 9/30/2008:

Your saved search titled "C-Level Executive, Vice-President, Director" matched new jobs based on your search criteria. Listed below are the top 10 match(es)... (Just click on the job title to view a job.)

1. Sep, 30, Mechanic, Energi Personnel
2. Sep, 30, Weight Loss Management, Consultant
3. Sep, 30, MECHANICS, Company Confidential
4. Sep, 30, Prevention/ Tobacco Specialist
5. Sep, 30, Horse Stall Cleaner/Groomer, Post Electric Inc
6. Sep, 30, RN, Permian Endoscopy Center
7. Sep, 30, Director - Maintenance, Operat, Company Confidential
8. Sep, 30, DRIVER WITH OIL DELIVERY EXPERIENCE NEED
9. Sep, 30, Clerical/Secretarial Customer, Company Confidential
10. Sep, 30, Management assistant store ma, Company Confidential

This email notification may contain only a partial list of all your saved search results.
Click here to see all results.

Saturday, September 6, 2008

Nortel goes Machievelian against Cisco with new TV advertisement

Wow, I just saw a TV spot that would make Machiavelli proud. After little research I find out some very, very interesting facts. The very thing a they teach you good advertisement should do. Bravo ad guys, job VERY well done!

The ad I'm talking about is visually, very simple, and consists of people sitting in front of stacks of money. We aren't talking little stacks of money, more like "I just knocked off an armored truck"-sized stacks of money. As the camera slowly pans in, and melodramatic music plays, each of those people simply say the total amount of the stack sitting in front of them. "192,186 Dollars", "678,477 Dollars", "356,931 Dollars", "1,358,907 Dollars". On that last one the accountant sitting next to him chimes in "and 41 cents". I thought to myself "that was a well-played humorous twist". As the commercial played, and I felt the music and camera work do its magic on my emotions, I put down the box of takeout chinese I had been stuffing into my face and paid close attention to the details of the TV spot. I roll my eyes as I realize I am probably watching the latest Republican "fear Obama spot". As usual, my mind races to find the punchline before it's shown. "Obama will raise taxes for the working class..." No, these are all business people and the numbers are too large... "Obama's tax increases will hurt small business owners..." that's a bit cheesy, but would the Republicans really be so desperate, especially after such a strong showing by Palin coming off the recent Republican convention? Ok, I can't figure it out where this is going, I am very interested in what the punchline is (as well as doing a tear-down analysis of the commercial as an example of a well done advertisement). Ah yes, the music crescendos and cuts out and in the next shot, the first guy shown looks up from his pile of money and says "I don't think I want to pay this any more." And then comes the punchline, The Cisco Energy "Tax". My eyebrows quickly crawled two inches up my forehead and my jaw drops. WHAT THE HELL IS THAT?!?! I quickly cracked my usual mischievous grin, laughed and said in disbelief "Who the hell is attacking Cisco?!?!" and at the same time got my answer on the screen, Nortel.

Ok, my current projects are moving at a break neck speeds and I have a backlog of clients and new projects, so I am a few months behind on reading my computer industry magazines, but I hadn't noticed any Nortel ads pushing the energy-efficiency angle. Two minutes later, I am at my desk Googling "Cisco energy tax" and getting back only 6,260 hits. "This has got to be something that's really, really new. Something worth blogging about." So here I am, sharing with you what I've found - and reverse engineering it with you in the way only a hacker could. First, lets start with the actual video on YouTube.

Thursday, July 31, 2008

First Post!!!

So, after ages of putting it off and making excuses like "I'll host the blog on my own server" I have finally broken down and setup a blog here at Blogger. I'll host it proper on my domain at a later time.