ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Implementing Mutual Exclusion for AJAX
Pages: 1, 2, 3

The Mutex constructor (lines 23-31) records its Command object and method name parameters and then registers itself into a sparse array of critical sections in progress (Mutex.Wait), which is implemented via the Map class shown in Listing 4. It then gets the "next number" and starts waiting at the end of the line. Since there is not a problem with gaps or duplicates in the wait numbers, the current timestamp is actually used as the "next" number.



The attempt() method combines the two wait loops in the original pseudocode into a single loop that doesn't fall through to the critical section until it is at the head of the line. This loop is a form of busy-wait polling, which can be throttled by the amount of delay specified in the setTimeout() call. Since setTimeout requires a "flat function" to be called, rather than an object method, a static helper method (Mutex.SLICE) is defined in lines 4-6. SLICE locates the specified Mutex object in the master wait list and calls its attempt() method, with the start parameter specifying how far through the wait list it has gotten so far. Each SLICE() call is like getting a "slice of CPU." This cooperative approach of yielding the CPU (via setTimeout) is reminiscent of coroutines.

function Map() {
  this.map  = new Object();
  // Map API
  this.add = function( k,o ){
    this.map[k] = o;
  }
  this.remove = function( k ){
    delete this.map[k];
  }
  this.get = function( k ){
    return k==null ? null : this.map[k];
  }
  this.first = function(){
    return this.get( this.nextKey() );
  }
  this.next = function( k ){
    return this.get( this.nextKey(k) );
  }
  this.nextKey = function( k ){
    for (i in this.map) {
      if ( !k ) return i;
      if (k==i) k=null; /*tricky*/
    }
    return null;
  }
}
Listing 4. Sparse array implemented as a Map data structure

Rich Internet Application Integration

Since Mutex handles a dynamic number of threads (virtual or not), one can get around the fact that an actual thread ID isn't known by acting as if the browser assigns a separate thread to each browser event. A similar simplifying assumption is that each complete event handler constitutes a complete critical section. Given these, each event handler function can be converted into a command object, and Mutex used to invoke and manage them. Of course, if the code is not already cleanly organized into event handling functions then refactoring will be needed. In other words, rather than encoding logic directly in HTML event attributes (e.g., onclick='++var'), define and invoke event handling functions (e.g., onclick='FOO()' and function FOO(){++var;}).

<html>
<script language="JavaScript">
  function newState(){
    if (XMLreq.readyState==4) processReply();
  }
  function requestData(){
      ...set up asynchronous XML request...
      XMLreq.onreadystatechange = newState;
      ...launch XML request...
  }
  function processReply(){
      var transformedData = ...process data to HTML...
      OutputArea.innerHTML = transformedData + "<br>";
  }
  function clearArea(){
      OutputArea.innerHTML = "cleared<br>"; 
  }
</script>
<body onload="requestData();">
 <input type="button" value="clear" onclick="clearArea()">
 <div id="OutputArea"/>
</body>
</html>
Listing 5. Example web page with unsynchronized event handlers

For example, suppose there are three event handler functions that manipulate common data as shown in Listing 5. They handle a page-load event, a button-clicked event and a reply-received-from-XML-request event. The page-load event handler launches some asynchronous request for data. It specifies the request-reply event handler, which processes the received data and loads it into a common data structure. The button-click handler also affects the common data structure. To keep these event handlers from conflicting, they can be converted to commands and invoked via Mutex as shown in Listing 6. (Assume that Map and Mutex are contained in the JavaScript include file mutex.js.) Note that, while elegant class inheritance mechanisms can be used to implement Command subclasses, this code illustrates a minimalist approach, requiring only the global variable NEXT_CMD_ID.

<html>
<script src="mutex.js"></script>
<script language="JavaScript">
  function requestData (){
    new Mutex(new  RequestDataCmd(),"go"); }
  function processReply(){
    new Mutex(new ProcessReplyCmd(),"go"); }
  function clearArea   (){
    new Mutex(new    ClearAreaCmd(),"go"); }
  function newState    (){
    if (XMLreq.readyState==4) processReply(); }

  var NEXT_CMD_ID = 0;

  function RequestDataCmd(){
    this.id = ++NEXT_CMD_ID;
    this.go = function(){
      ...set up asynchronous XML request...
      XMLreq.onreadystatechange = NewState;
      ...launch XML request...
    }
  }
  function ProcessReplyCmd(){
    this.id = ++NEXT_CMD_ID;
    this.go = function(){
      var transformedData = ...process data to HTML...
      OutputArea.innerHTML = transformedData + "<br>";
    }
  }
  function ClearAreaCmd(){
    this.id = ++NEXT_CMD_ID;
    this.go = function(){ 
      OutputArea.innerHTML = "cleared<br>"; }
  }
</script>
<body onload="requestData();">
 <input type="button" value="clear" onclick="clearArea()">
 <div id="OutputArea"/>
</body>
</html>
Listing 6. Web page converted to synchronized event handlers

The three event handler functions have been changed to invoke their original logic (each now wrapped in command classes) via Mutex. Each command class defines a unique ID and a method containing critical section logic, thus fulfilling the command interface requirements.

Conclusion

With AJAX and RIA, the impetus to build complicated dynamic user interfaces is driving developers to use the same design patterns (e.g. Model-View-Controller) formerly tied to "fat" GUI clients. With Views and Controllers being defined modularly, each with their own events and event handlers (but sharing common data models), the potential for conflicts multiply. By encapsulating event handling logic into Command classes, not only can the Wallace variation be employed, but the stage is also set to provide rich undo/redo functionality, scripting interfaces, and unit test instrumentation.

Resources

  • The sample code in this article is available for viewing or download. It includes the omitted details such that the web pages can execute directly in the browser without a server connection.
  • An example JavaScript framework (Gravy) that uses the techniques in this article is available for viewing or downloading, complete with JsDoc documentation. Gravy supports placing all application functionality in the browser in JavaScript. Applications need only access the server for database CRUD operations.

Bruce Wallace is principal consultant of PolyGlot, Inc.


Return to ONJava.com.