User Guide

Table Of Contents
Locking code with cflock 367
Copying shared variables into the Request scope
You can avoid locking some shared-scope variables multiple times during a request by doing the
following:
1.
Copy the shared-scope variables into the Request scope in code with an exclusive lock in the
Application.cfc
onRequestStart method or the Application.cfm page.
2.
Use the Request scope variables on your ColdFusion pages for the duration of the request.
3.
Copy the variables back to the shared scope in code with an exclusive lock in the Application.cfc
onRequestEnd method on the OnRequestEnd.cfm page.
With this technique the “last request wins.” For example, if two requests run simultaneously, and
both requests change the values of data that was copied from the shared scope, the data from the
last request to finish is saved in the shared scope, and the data from the previous request is not
saved.
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:
<!--- Initialize 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