User Guide

Table Of Contents
Locking code with cflock 361
Similarly, ColdFusion MX cannot automatically ensure that two sections of code do not attempt
to access external resources such as files, databases, or CFX tags that cannot properly handle
simultaneous requests. Nor can ColdFusion MX ensure that the order of access to these shared
resources is consistent and results in valid data.
By locking code that accesses such resources so that only one thread can access the resource at a
time, you can prevent race conditions.
Sample locking scenarios
The following examples present scenarios in which you need to lock ColdFusion code. These
scenarios show only two of the circumstances where locking is vital.
Reading and writing a shared variable
If you have an application-wide value, such as a counter of the total number of tickets sold, you
might have code such as the following on a login page:
<cfset Application.totalTicketsSold = Application.totalTicketsSold +
ticketOrder>
When ColdFusion executes this code, it performs the following operations:
1.
Retrieves the current value of Application.totalTicketsSold from temporary storage.
2.
Increments this value.
3.
Stores the result back in the Application scope.
Suppose that ColdFusion processes two ticket orders at approximately the same time, and that the
value of Application.totalTicketsSold is initially 160. The following sequence might happen:
1.
Order 1 reads the total tickets sold as 160.
2.
Order 2 reads the total tickets sold as 160.
3.
Order 1 adds an order of 5 tickets to 160 to get 165.
4.
Order 2 adds an order of 3 tickets to 160 to get 163.
5.
Order 1 saves the value 165 to Application.totalTicketsSold
6.
Order 2 saves the value 163 to Application.totalTicketsSold
The application now has an inaccurate count of the tickets sold, and is in danger of selling more
tickets than the auditorium can hold.
To prevent this from happening, lock the code that increments the counter, as follows:
<cflock scope="Application" timeout="10" type="Exclusive">
<cfset Application.totalTicketsSold = Application.totalTicketsSold +
ticketOrder>
</cflock>