Submitted by Brad J. Gallagher, email@example.com
One very powerful tool in the ColdFusion arsenal is the capability to use session variables. As with all other powerful tools, using session variables with care is important. Using proper coding procedures, session variables can speed up code, allow for cleaner application planning, and ease administration. With improper coding practices, using session variables can bring a server to its knees.
Like other variables with persistent scope, session variables need to be protected from simultaneous read/write access. Without such protection, data corruption can occur when several threads have access to the same session variable. In certain cases, improper use of just one session variable can hang the ColdFusion Server!
One tactic when working with a file that has a large number of read/ write requests to multiple session variables is to copy data from persistent scope to local scope. After all computation is done, copy the results back into persistent scope. This will drastically reduce the number of CFLOCK tags required and will eliminate the possibility of neglecting to properly protect a session variable. Remember that it takes just one unprotected session variable to kill the server.
All session data is stored into a structure named session. To copy this to local scope, a developer could do the following:
<cflock scope="SESSION" type="READONLY" timeout="10"> <cfset local.sessionvars = structNew()> <cfset local.sessionvars = duplicate(session)> </cflock>
The developer could then read/write to the local variable local.sessionvars.foo as many times as needed in the page without fear of data corruption. After all computation is done, return the results to persistent scope at the end of the file. We can do this by copying our local data back into the structure session, like this:
<cflock scope="SESSION" type="exclusive" timeout="10"> <cfset session.foo = duplicate(local.sessionvars.foo)> </cflock>