Thread safety and the var scope - live example

Recently, I've talked to a few developers who knew about the var scope, but didn't quite grasp the concept of making a variable local to a function. Additionally, I've come across a few posts that indicated that setting a var statement was strictly to conserve memory (along with other reasons that missed the point).

To help anyone struggling with understanding the impact of the var scope I've put together a quick example to demonstrate what can happen when you improperly scope a variable.

The example here focuses on CFCs that are loaded into a shared scope (session, application, etc), and are accessed simultaneously by multiple users.Running the code will make 2 simultaneous requests to the same function in separate iframes. The example contains a loop that outputs the index of a loop from 1 to 100. If the loop executes correctly the numbers appear in green, if the numbers are out of sequence, they will be red. To make the results more dramatic I've included a 1-40ms pause in each loop iteration.

run example with var statement
run example without var statement

Here's the cfc that is loaded in server scope (simplified for reading). Note the only difference in the functions is that the "count" variable has a var statement in one function and doesn't in the other function.

<cfcomponent name="thread">
   
   <cffunction name="nonVarFunction" >
      <cfset var lastCount = 0>
      <cfset var idx = 0>
      
      <cfset count = 0>
      
      executing "nonVarFunction()"<br/>
      
      <cfloop from="1" to="100" index="idx">
         <cfset lastCount = count>
         <cfset count = count + 1>
         <cfthread action="sleep" duration="#randRange(1,40)#" />
         <cfoutput>
            <cfif count-1 EQ lastCount>
             <!--- display green--->
             #count#
            <cfelse>
             <!--- display red--->
             #count#
            </cfif>
         </cfoutput>
         <cfflush>
      </cfloop>
   </cffunction>
   
   <cffunction name="VarFunction" >
      <cfset var lastCount = 0>
      <cfset var idx = 0>
      
      <cfset var count = 0>
      
      executing "VarFunction()"<br/>
      
      <cfloop from="1" to="100" index="idx">
         <cfset lastCount = count>
         <cfset count = count + 1>
         <cfthread action="sleep" duration="#randRange(1,40)#" />
         <cfoutput>
            <cfif count-1 EQ lastCount>
             <!--- display green--->
             #count#
            <cfelse>
             <!--- display red--->
             #count#
            </cfif>
         </cfoutput>
         <cfflush>
      </cfloop>
   </cffunction>
</cfcomponent>

What happened?

If the example executed correctly, you should have seen all green numbers in both windows for the var scope example, and a mix of green and red in the example that executed the function without the var statement. The presence of the "var" statement makes the variable local to the function. This means that when the function runs, it creates a new instance of the variable that is unique each time the function is executed. Without the var statement in place, the variable gets "shared" between everyone who is accessing this component. When a component lives in a shared scope (session, application) the variable will be shared for everyone accessing that scope. Think of the following scenario.

User 1: set count = 1
User 2: set count = 1
User 1: set count = count + 1
User 2: set count = count + 1
User 1: count = 2
User 2: count = 3

In this case the developer most likely intended to have both users see count = 2, however the variable was shared and as a result a user's result was impacted by another user's request. Note: this may be the intended behavior of the code, and that's why there is no definite rule on why you should "always" or "never" var scope a variable.

Unfortunately, recognizing issues that appear as a result of improper scope can be difficult. Many times they result in server errors that are intermittent and only appear under load. This can sometimes make it practically impossible to reproduce the error in a test environment. Also, many tags create variables that are easy to miss (cfquery, cfloop, etc).

Luckily, there's a tool to help (shameless plug here). Take a look at varscoper. Hopefully this will become an integral tool in your development process.

New varScoper release candidate

A new release candidate is available for my varScoper tool.

varscoper_1_30_RC.zip

Please download and run against your code. If you find any issues please report them at RIAForge.

Thank you to everyone who provided feedback on 1.21. At least 16 bugs were identified and are now fixed in the RC. All reported issues and corner cases have been added to the unit test to ensure that it won't break the same way in the future. Additionally, thank you to Pat Santora, who was responsible for a majority of the fixes.

Finally, based on feedback, I've included a cfset statement generator to generate blocks of cfset var statements. However, I take no responsibility for the consequences of using this generated code.

quick varScoper update

Version 1.21 of varscoper is now available to download . This is a minor update that fixes some of the CF6, CF7, and *nix issues that were reported when I released 1.20.

Additionally, there was a minor fix to cfscript parsing when using a function inside a struct set. Something similar to this...

mystruct[someFunction()] = "";

varScoper 1.20 - critical update

Version 1.20 of varscoper is now out on RIAForge. It's also available directly from the download link.

Many thanks to Pat Santora for this release. The majority of the content in this release is a direct result of his hard work.

Updates

  • Improvements to cfscript parsing engine
    • RIAForge issues 6,7,8,9,10,11 are fixed
    • Improved handling of script comments
  • Ability to exclude files/folders
    • configured through properties.xml
    • Ability to exclude individual files or directories from your search
  • Integrated Unit Testing
    • testCaseCFC.cfc now includes positive/negative test cases for all reported issues
    • Currently still reporting 2 known issues that will be addressed in a future release
  • Improvements to parsing engine
    • Fix for Ray's cffeed bug (also fixes cfprocparam)
    • More agressive var scope checking (re-run against all your code, we found 2 new unscoped vars at Planitax)

More Entries

BlogCFC was created by Raymond Camden. This blog is running version 5.9.002. Contact Blog Owner