User Guide

Table Of Contents
Locking code with cflock 363
Using the cflock tag with write-once variables
You do not need to use
cflock when you read a variable or call a user-defined function name in
the Session, Application, or Server scope if it is set in only one place in the application, and is only
read (or called, for a UDF) everywhere else. Such data is called write-once. If you set an
Application or Session scope variable in Application.cfm and never set it on any other pages, you
must lock the code that sets the variable, but do not have to lock code on other pages that reads
the variables value. If you set the variable in the corresponding start method in Application.cfc
(for example,
onApplicationStart for Application scope variables), you do not have to lock the
code that sets the variable.
However, although leaving code that uses write-once data unlocked can improve application
performance, it also has risks. You must ensure that the variables are truly written only once. For
example, you must ensure that the variable is not rewritten if the user refreshes the browser or
clicks a back button. Also, it can be difficult to ensure that you, or future developers, do not later
set the variable in more than one place in the application.
Using the cflock tag
The
cflock tag ensures that concurrently executing requests do not run the same section of code
simultaneously and thus manipulate shared data structures, files, or CFX tags inconsistently. It is
important to remember that
cflock protects code sections that access or set data, not the
variables themselves.
You protect access to code by surrounding it in a
cflock tag; for example:
<cflock scope="Application" timeout="10" type="Exclusive">
<cfif not IsDefined("Application.number")>
<cfset Application.number = 1>
</cfif>
</cflock>
Lock types
The
cflock tag offers two modes of locking, specified by the type attribute:
Exclusive locks (the default lock type) Allow only one request to process the locked code. No
other requests can run code inside the tag while a request has an exclusive lock.
Enclose all code that creates or modifies session, application, or server variables in exclusive
cflock tags.
Read-only locks Allow multiple requests to execute concurrently if no exclusive locks with the
same scope or name are executing. No requests can run code inside the tag while a request has an
exclusive lock.
Enclose code that only reads or tests session, application, or server variables in read-only
cflock
tags. You specify a read-only lock by setting the
type="readOnly" attribute in the cflock tag,
for example:
<cflock scope="Application" timeout="10" type="readOnly">
<cfif IsDefined("Application.dailyMessage")>
<cfoutput>#Application.dailyMessage#<br></cfoutput>