Lately I've been noticing, while examining chunks of ColdFusion code out there, that many folks don't give much thought to what goes on inside their <cflock> tags. In the case where you're locking a session scope, so you can update session variables for example, the amount of code executed inside the lock should be as short as possible.
As an example, take a look at this unnecessarily long lock:
<cflock scope="session" type="readonly" timeout="5">
<cfset variables.calc = 0>
<cfloop from="1" to="100000" index="i">
<cfset variables.calc = variables.calc + i>
</cfloop>
<cfset session.calc = calc>
</cflock>
Why anyone would store the results of the calculation above in a session variable is beyond me! But, it's a great example of what not to do.
The session lock above is held while the <cfloop> of 100,000 iterations is run.
This code is better executed as below:
<cfset variables.calc = 0>
<cfloop from="1" to="100000" index="i">
<cfset variables.calc = variables.calc + i>
</cfloop>
<cflock scope="session" type="readonly" timeout="5">
<cfset session.calc = calc>
</cflock>
The same rule would apply to any web development language that offers session management.