User Guide

Table Of Contents
Locking code with cflock 365
Controlling locking access to files and CFX tags with the name attribute
The cflock name attribute provides a second way to identify locks. Use this attribute when you
use locks to protect code that manges file access or calls non-thread-safe CFX code.
When you use the
name attribute, specify the same name for each section of code that accesses a
specific file or a specific CFX tag.
Controlling and minimizing lock time-outs
You must include a
timeout attribute in your cflock tag. The timeout attribute specifies the
maximum time, in seconds, to wait to obtain the lock if it is not available. By default, if the lock
does not become available within the time-out period, ColdFusion generates a Lock type
exception error, which you can handle using
cftry and cfcatch tags.
If you set the
cflock throwOnTimeout attribute to No, processing continues after the time-out at
the line after the
</cflock> end tag. Code in the cflock tag body does not run if the time-out
occurs before ColdFusion can acquire the lock. Therefore, never use the
throwOnTimeout
attribute for CFML that must run.
Normally, it does not take more than a few seconds to obtain a lock. Very large time-outs can
block request threads for long periods of time and radically decrease throughput. Always use the
smallest time-out value that does not result in a significant number of time-outs.
To prevent unnecessary time-outs, lock the minimum amount of code possible. Whenever
possible, lock only code that sets or reads variables, not business logic or database queries. One
useful technique is to do the following:
1.
Perform a time-consuming activity outside of a cflock tag
2.
Assign the result to a Variables scope variable
3.
Assign the Variables scope variable’s value to a shared scope variable inside a cflock block.
For example, if you want to assign the results of a query to a session variable, first get the query
results using a Variables scope variable in unlocked code. Then, assign the query results to a
session variable inside a locked code section. The following code shows this technique:
<cfquery name="Variables.qUser" datasource="#request.dsn#">
SELECT FirstName, LastName
FROM Users
WHERE UserID = #request.UserID#
</cfquery>
<cflock scope="Session" timeout="5" type="exclusive">
<cfset Session.qUser = Variables.qUser>
</cflock>