Contents > Developing ColdFusion MX Applications > Using Persistent Data and Locking > Locking code with cflock > Nesting locks and avoiding deadlocks Locking application variables efficiently PreviousNext

Locking application variables efficiently

The need to lock application variables can reduce server performance, because all requests that use Application scope variables must wait on a single lock. This issue is a problem even for write-once read-many variables, because you still must ensure the variable exists, and possibly set the value before you can read it.

You can minimize this problem by using a technique such as the following to test for the existence of application variables and set them if they do not exist:

  1. Use an Application scope flag variable to indicate if the variable or variables are initialized. In a read-only lock, check for the existence of the flag, and assign the result to a local variable.
  2. Outside the cflock bock, test the value of the local variable
  3. If it the local variable indicates that the application variables are not initialized, get an exclusive Application scope lock.
  4. Inside the lock, again test the Application scope flag, to make sure another page has not set the variables between step one and step four.
  5. If the variables are still not set, set them and set the Application scope flag to true.
  6. Release the exclusive lock.

The following code shows this technique:

<!--- Initilialize local flag to false --->
<cfset app_is_initialized = False>
<!--- Get a readonly lock --->
<cflock scope="application" type="readonly">
   <!--- read init flag and store it in local variable --->
   <cfset app_is_initialized = IsDefined("APPLICATION.initialized")>
</cflock>
<!--- Check the local flag --->
<cfif not app_is_initialized >
<!--- Not initialized yet, get exclusive lock to write scope --->
   <cflock scope="application" type="exclusive">
      <!--- Check nonlocal flag since multiple requests could get to the
            exclusive lock --->
      <cfif not IsDefined("APPLICATION.initialized") >
         <!--- Do initializations --->
         <cfset APPLICATION.varible1 = someValue >
          ... 
         <!--- Set the Application scope initialization flag --->
         <cfset APPLICATION.initialized = "yes">
      </cfif>
   </cflock>
</cfif>

Contents > Developing ColdFusion MX Applications > Using Persistent Data and Locking > Locking code with cflock > Nesting locks and avoiding deadlocks Locking application variables efficiently PreviousNext

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | Bug Reporting

Version 6.1

Comments are no longer accepted for ColdFusion MX 6.1. ColdFusion 8 is the current version.