ColdFusion Struct Literals Are Not Thread Safe (CFML Ones Are)

If you read my blog regularly or follow me on Twitter, you know how much I hate Adobe's quasi-implementation of struct (and array) literals.  I'm really hoping "third time's a charm" and CF9's implementation is sane.  The gripe is that this code:

<cfset s = {
  name = "barney",
  age = 29
} />

is executed as if it were written like this (on Adobe ColdFusion):

<cfset s = structNew() />
<cfset s.name = "barney" />
<cfset s.age = 29 />

The "correct" behaviour is to execute it as if it were written like this (which is how Railo does it):

<cfset temp = structNew() />
<cfset temp.name = "barney" />
<cfset temp.age = 29 />
<cfset s = temp />

This lets you write some really nasty code, causes some weird bugs, and today I realized (through some handy errors on our production cluster) that there are thread safety issues as well.   Consider this code (inside a getCacheForKey() method):

<cfif NOT structKeyExists(key_stats_cache, key)>
<cflock name="getCacheForKey.#key#" type="exclusive" timeout="1">
<cfif NOT structKeyExists(key_stats_cache, key)>
  <cfset key_stats_cache[key] = {
    getCount = 0,
    staleGetCount = 0,
    missCount = 0
  } />
</cfif>
</cflock>
</cfif>

If the struct literal were an expression, this code would be thread safe, because the assignment to 'key_stats_cache[key]' would be atomic.  However, because of the way ColdFusion implements it, it's not thread safe.  It's possible to have the existence checks trigger in a second request while the struct is building in the first request, and therefore some keys will not be present after the outer </cfif> tag of a second request.  Wrapping the outer <cfif> tag with a read-only CFLOCK will address the issue, of course, but if struct literals were implemented as expressions (the second behaviour above), the problem could never manifest itself.  So watch out!  Atomicity of assignment statements is not assured.

3 responses to “ColdFusion Struct Literals Are Not Thread Safe (CFML Ones Are)”

  1. Luis majano

    That is truly disturbing!!

  2. ColdFusion Struct Literals Are Not Thread Safe (CFML Ones Are) | Adobe Tutorials

    [...] If you read my blog regularly or follow me on Twitter, you know how much I hate Adobe's quasi-implementation of struct (and array) literals.  I'm really hoping "third time's a charm" and CF9's implementation is sane.  The gripe is that this code: is executed as if it were written like this (on Adobe ColdFusion): The "correct" behaviour is to execute it as if it were written like this (which is how Railo does it): This lets you write some really nasty code , causes some w Read more: ColdFusion Struct Literals Are Not Thread Safe (CFML Ones Are) [...]

  3. Mike Causer

    argh, you made me spill my coffee…