Is your code Thread Safe? How do you know?

Code that is not Thread Safe is sneaky, dangerous and leads to bewildering production errors and strange side effects.

As part of my deployment procedure, I run code through an automated code analyzer for improperly scoped variables. Today, while running the analyzer, it flagged this set of code:

<cfset var ExistingRiskValuesList = "" />   
<cfset ExistingRiskValueList = valuelist( RiskAssessmentQuery.TotalLeaseRisk ) >

"Wait just a minute", I said, "There is nothing wrong with that bit of code". Upon closer inspection I noted the 's' and quickly made the correction. Had I not used the automated code analyzer, this Thread-Unsafe code would have went into production.

There are many good posts about var scoping your variables, should you need more convincing. Mike Schierberl actually made and posted a video showing a memory leak in action caused by code that is not thread safe and Mike also gives away the automated code analyzer. If you haven't yet, I challenge you to download it and run it against some code. You might be surprised!

Update: Mike Schieberl and Zac Spitzer have made some improvements to the Var Scoper tool. The tool parses cfscript and is now hosted on http://varscoper.riaforge.org/ . Thanks Mike and Zac for the fine work on one of the most important code checking tools out there!

Comments
Thanks, this should be really helpful. What I've started doing to check for these types of problem is to use a temporary function to dump out the variables scope from a cfc. I'll run various test code that go through many scenarios then dump out the object's variables scope and spot check it.

If you use a struct in the variables scope (ex. variables.instance) for protected properties then nothing but that struct and functions should be in variables scope from my recollection. I just put the dump function in the cfc temporarily but I guess it could be added with IOC to any function. I bet this could be checked in conjunction with automated unit testing.
# Posted By Dan Roberts | 9/27/07 11:31 PM
Wow, this is great stuff.

I used a fair bit of CFSCRIPT and it was throwing false positives, so I got inspired with some hacking round and i have a script parser for only finding var cfscript variables in a CFC. The code also knows how to ignore comments which is important in CFSCRIPT.

Dan, I am emailing you a copy of mods
# Posted By zac spitzer | 9/28/07 4:29 AM
Zac, is it possible that you can share your mods?
# Posted By Dmitriy Goltseker | 9/28/07 9:45 AM
# Posted By zac spitzer | 9/28/07 11:45 AM
Dan ran some test cases and found a bug in the way i was handling // comments

updated code is here, Mike is going to add this to RIAforge, sweet!
http://zacster.blogspot.com/2007/10/updated-varsco...
# Posted By zac spitzer | 10/2/07 4:08 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.001. Contact Blog Owner